这是一个刚入手R的心急的人提的问题。 我有一个文件包含这样的行:
simulation_time:386300;real_time:365;agents:300
simulation_time:386800;real_time:368;agents:300
simulation_time:386900;real_time:383;agents:300
simulation_time:387000;real_time:451;agents:300
simulation_time:387100;real_time:345;agents:300
simulation_time:387200;real_time:327;agents:300
simulation_time:387300;real_time:411;agents:300
simulation_time:387400;real_time:405;agents:300
simulation_time:387500;real_time:476;agents:300
simulation_time:387600;real_time:349;agents:300
....
需要从文件中绘制图表。 This link教导如何通过读取表格格式的文件来绘制文件。但以上几行不是表格格式或简洁的 csv 格式。
你能告诉我如何解析这样的文件吗?
另外,如果你对像我这样没有耐心的人有引用,请告诉我。
谢谢
最佳答案
如果文件结构严格,那么你可以自定义你的阅读以获得你想要的数据。 请参阅下面的代码。
# reading the file
strvec = readLines(con = "File.txt", n = -1)
# strsplit by ";" or ":"
strlist = strsplit(strvec,":|;")
# changing to matrix (works only if the structure of each line is the same)
strmat = do.call(rbind, strlist)
# lets take only numbers
df = strmat[ ,c(2,4,6)]
# defining the names
colnames(df) = strmat[1 ,c(1,3,5)]
# changing strings to numerics (might be better methods, have any suggestions?)
df = apply(df, 2, as.numeric)
# changing to data.frame
df = as.data.frame(df)
# now you can do that ever you want
plot(df$simulation_time, type="l")
关于r - 如何解析自定义格式的文件 R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21773513/