2014-02-14 29 views
0

這是一個剛剛開始工作R的不耐煩的人提出的問題。 我有一個包含這樣行的文件:如何解析自定義格式文件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格式。

請問如何解析這樣的文件?

此外,如果你有像我這樣的不耐煩的人,請告訴我。

感謝

回答

2

如果文件的結構是嚴格的,那麼你可以定製你的閱讀來獲得你想要的數據。 請參閱下面的代碼。

# 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") 
+0

Spacedman的回答更專業。但是這對初學者來說更好,因爲它已經將其分解爲幾個步驟。謝謝你們倆 – rahman

4

因爲在這樣的精確格式的數據:

d = read.csv(textConnection(gsub(";",":",readLines("data.csv"))),sep=":",head=FALSE)[,c(2,4,6)] 

生產:

 V2 V4 V6 
1 386300 365 300 
2 386800 368 300 
3 386900 383 300 
4 387000 451 300 

然後你可以names(d)=c("sim","real","agents")指定名稱的數據幀。

它通過將文件讀入字符向量來取代「;」使用「:」,因此所有內容都以「:」分隔,然後使用read.csv將該文本讀入數據框,然後僅取數據列而不是重複的文本列。