2014-03-12 209 views
3

我有一個大表讀入R,並且該文件格式爲.txt。在R,我使用read.table功能,但有錯誤在讀它出現以下錯誤消息:用於讀取R中不完整數據的read.table函數

Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : 
    line 28 did not have 23 elements 

似乎(從第1行計數不脫離如I所指明skip=計數報頭),數據在第28行中缺少元素。我正在尋找一種方法來自動通過更正此問題此行。現在,我甚至不可能在文件中讀取,所以我不能在R中操縱...任何建議都非常感謝:)

回答

3

這裏是我的方法:撥打電話read.table與選項fill=TRUE ,並排除後面沒有填滿所有字段的行(撥打電話count.fields)。

例子:

# 1. Data generation, and saving in 'tempfile' 
cat("1 John", "2 Paul", "7 Pierre", '9', file = "tempfile", sep = "\n") 

# 2. read the data: 
data = read.table('tempfile',fill=T) 

# 3. exclude incomplete data 
c.fields = count.fields('tempfile') 
data = data[ - (which(c.fields) != max(c.fields)),] 

(編輯自動獲取的行數)

2

該錯誤也發生時,你在你的數據的哈希符號(#)。

如果是這樣的情況下,只需選擇comment.char更改爲comment.char = ""

read.table("file.txt", comment.char = "") 
+0

謝謝!這是一個非常有用的信息! – alittleboy