更改read.table用于确定R中列数的行数

时间:2013-05-16 10:13:09

标签: r read.table

?read.table中声明:

The number of data columns is determined by looking at the first five lines of input
(or the whole file if it has less than five lines), or from the length of col.names
if it is specified and is longer. This could conceivably be wrong if fill or
blank.lines.skip are true, so specify col.names if necessary (as in the ‘Examples’).

我需要使用fill参数,并且我的一些txt文件可能在第5行之后具有最高列数的行。我不能使用标题,只是因为我没有它,并且导入后将定义col.names,所以我想将R使用的这5行更改为整个文件,(我不知道)记住我能得到的任何速度损失)。有什么建议吗?谢谢!

编辑:

read.table

的代码中找到了这个
if (skip > 0L) 
    readLines(file, skip)
nlines <- n0lines <- if (nrows < 0L) 
    5
else min(5L, (header + nrows))
lines <- .External(C_readtablehead, file, nlines, comment.char, 
    blank.lines.skip, quote, sep)
nlines <- length(lines)

我可以在上面代码的第4行中更改数字5吗?是否会对read.table行为产生任何副作用?

编辑2:

我目前正在使用此方法

maxCol <- max(sapply(readLines(filesPath), function(x) length(strsplit(x, ",")[[1]])))

拥有最大列数,并将结果设置为创建虚拟col.names,如paste0("V", seq_len(maxCol))。你认为让另一个read.table有可能选择那个仍然值得吗?

1 个答案:

答案 0 :(得分:4)

使用count.fields,例如

read.table(filesPath, colClasses=rep(NA, max(count.fields(filesPath))), fill=TRUE)
相关问题