使用read.table监视R数据加载进度

时间:2011-06-15 19:39:37

标签: r progress-bar read.table

我已经为其他类型的数据加载找到了很多答案,但是当R使用read.table(...)读取数据时没有显示进度。我有一个简单的命令:

data = read.table(file=filename,
                sep="\t",
                col.names=c("time","id","x","y"),
                colClasses=c("integer","NULL","NULL","NULL"))

这会在大约30秒左右加载大量数据,但进度条非常好:-D

1 个答案:

答案 0 :(得分:2)

继续实验:

构建临时工作文件:

n <- 1e7
dd <- data.frame(time=1:n,id=rep("a",n),x=1:n,y=1:n)
fn <- tempfile()
write.table(dd,file=fn,sep="\t",row.names=FALSE,col.names=FALSE)

使用read.table(包含和未指定colClasses)和scan运行10次重复:

修改:更正scan来回复评论,更新结果:

library(rbenchmark)
(b1 <- benchmark(read.table(fn,
                     col.names=c("time","id","x","y"),
                            colClasses=c("integer",
                              "NULL","NULL","NULL")),
                 read.table(fn,
                            col.names=c("time","id","x","y")),
          scan(fn,
               what=list(integer(),NULL,NULL,NULL)),replications=10))

<强>结果:

2 read.table(fn, col.names = c("time", "id", "x", "y"))
1 read.table(fn, col.names = c("time", "id", "x", "y"), 
      colClasses = c("integer", "NULL", "NULL", "NULL"))
3  scan(fn, what = list(integer(), NULL, NULL, NULL))

  replications elapsed relative user.self sys.self 
2           10 278.064 1.857016   232.786   30.722    
1           10 149.737 1.011801   141.365    2.388  
3           10 143.118 1.000000   140.617    2.105  

(警告,这些值略微变熟/不一致,因为我重新运行了基准并合并了结果......但定性结果应该没问题。)

没有read.table

colClasses最慢(这并不奇怪),但在此示例中,只有(?)比scan慢约85%。 <{1}}仅比指定scan的{​​{1}}快一点。

使用read.tablecolClasses,可以编写使用scanread.tableskip)或{{1}的“分块”版本}(nrows)参数一次读取文件的位,然后在最后将它们粘贴在一起。我不知道这会减慢这个过程的速度,但它会允许在块之间调用read.table ......