2013-04-08 23 views
1

請看照片。我已經開始使用R,並且知道如何/它可以從Excel中讀取文件,但它是否可以讀取像這樣的格式?組織在多個嵌套行中的Excel數據可以讀取嗎?

http://www.flickr.com/photos/[email protected]/8632809494/

(我的道歉,上傳不工作對我來說)

+0

是的。但它需要一些正則表達式和分裂foo。 – 2013-04-08 20:06:47

+0

我覺得可以。我會研究這些方法,感謝您指引我朝着正確的方向。 – Lorenzo 2013-04-08 20:10:42

+0

沒有一個可重複的例子,恐怕我們能做的很少。我們先將數據轉化爲R。您是否嘗試過使用旨在讀取excel文件的函數來讀取文件? – 2013-04-08 20:14:09

回答

0

在闡述一些什麼的評論:

如果您將文件加載到Excel中,您可以將其保存爲一個固定寬度或逗號分隔的文本文件。要麼很容易讀入R.

以下內容可能已經很明顯。

(首先,一個問題:您確定無法獲取每行有一組數據的格式的數據嗎?您獲得的文件是否可能是由不同的文件格式生成的這更有利於將數據加載到R中)

是否應該開始重新排列R中的數據,或者改爲處理原始文本取決於您自然而然(或您周圍有誰可以幫助的人)。對我個人而言,我將在R之外重新排列R之外的文本文件,這對我來說是最簡單的。爲此,Perl是一種很好的語言,但如果您可以訪問,或者使用Vim或Emacs等強大的編輯器,您也可以使用Unix shell腳本來完成此任務。如果你沒有偏好,我會建議Perl。如果你有任何重要的編程經驗,你將能夠了解你需要什麼。另一方面,你已經將它加載到R中,所以也許在那裏處理數據會更好。

例如,您可以執行一個循環,通過線變爲文本文件線做這樣的事情:

while (still have lines to read) { 
    read first header line into an vector if this is the first time through the loop 
    otherwise, read it and throw it away 
    read data line 1 into an vector 
    read second header line into vector if this is the first time 
    otherwise, read it and throw it away 
    read data line 2 into an vector 
    read third header line into vector if this is the first time 
    otherwise, read it and throw it away 
    read data line 3 into an vector 
    if this is first time through, concatenate the header vectors; store as next row 
    in something (a file, a matrix, a dataframe, etc.) 
    concatenate the data vectors you've been saving, and store as next row in same thing 
} 

write out the whole 2D data structure 

或者,如果標題不會改變,那麼你可以只將它們嵌入字面上進入循環前的腳本,並將其扔出去,無論如何。這將使代碼更清潔。或者單獨讀取文件的前幾行以獲取標題,然後使用單獨的腳本讀取數據並將其添加到包含標題的文件中。 (頭文件可能在R中有用,所以我建議將它們保存在文本文件的頂部。)