2014-03-12 205 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