2016-06-06 69 views
1

我有以下格式的文本文件,我對兩列數字的中間部分感興趣。如何通過R讀取此文本文件。如何在R中的文本文件中提取數字

Correct for Electrical Dark: No (NI25D137) 
Strobe/Lamp Enabled: No (NI25D137) 
Correct for Detector Non-linearity: No (NI25D137) 
Correct for Stray Light: No (NI25D137) 
Number of Pixels in Processed Spectrum: 256 
Begin Processed Spectral Data 
857.97 0.000 
864.83 7.252 
871.70 7.252 
878.56 7.155 
885.42 7.131 
892.27 7.113 
End Processed Spectral Data 
+0

您的數據實際上是在每行之間有行,還是在這裏粘貼的結果呢? – thelatemail

+0

不,它沒有行之間 –

回答

2

您可以使用readLines逐行讀取。然後,使用一些正則表達式可以保留數字行。在使用read.table將已清除的文本轉換爲data.frame之前,我也將開頭刪除多餘的空格。

ll <- readLines(con = textConnection("COPY YOUR TEXT HERE")) 
read.table(text=gsub("^ +","",grep("\\d+[.]\\d+ +\\d+[.]\\d+",ll,value=TRUE))) 

    V1 V2 
1 857.97 0.000 
2 864.83 7.252 
3 871.70 7.252 
4 878.56 7.155 
5 885.42 7.131 
6 892.27 7.113 
+0

有沒有什麼辦法可以通過直接訪問.txt文件來做到這一點? –

+0

@PrabeshJoshi當然是。您只需用文件名替換con = ...。 'readlines方法(path_filename)'。 – agstudy

相關問題