快速将大型平面文件读入r as.numeric

Tom*_*ith 1 r flat-file bigdata

我有一个大的(450MB/2.5亿行)1s和0s的平面文件,看起来像这样......

    1
    0
    0
    1
    0
    1
    0
    etc...
Run Code Online (Sandbox Code Playgroud)

我使用以下方法将其读入R ...

dat <- as.numeric(readLines("my_large_file"))
Run Code Online (Sandbox Code Playgroud)

我得到了理想的数据结构,但需要很长时间.有什么建议可以更快的方法来达到相同的效果吗?

NB.1和0的顺序对于保存很重要.我会在unix命令行的python中考虑选项,但是在R中需要最终的数据结构来绘制图形.

Ric*_*ven 5

scan对于只需要返回向量的数字文件,您可能会做得更好 .

scan("my_large_file", what = integer())
Run Code Online (Sandbox Code Playgroud)

what参数将加快文件的读取速度(而不是将其删除),因为您实际上告诉R它将读取整数值.scan也有派上用场的大数字文件(如许多其他的参数skip,nlines等等)

另外,正如@baptiste在评论中提到的那样,

library(data.table)
fread("my_large_file")
Run Code Online (Sandbox Code Playgroud)

既打击readLinesscan远(我的机器上).

注意:可能是一个错字,但在你的原始帖子中,我认为readlines应该是readLines


Jos*_*ich 5

时间比较几个选项.首先,一些数据.

set.seed(21)
x <- sample.int(2, 25e6, TRUE) - 1L
writeLines(as.character(x),"data")
Run Code Online (Sandbox Code Playgroud)

现在,一些基准测试(每个基准测试从新的R会话运行以避免文件被缓存).

> system.time(r <- as.numeric(readLines("data")))
   user  system elapsed 
  5.235   0.447   5.681 
> system.time(r <- scan("data",what=numeric()))
Read 25000000 items
   user  system elapsed 
  4.199   0.286   4.483 
> system.time(r <- scan("data",what=integer()))
Read 25000000 items
   user  system elapsed 
  3.134   0.081   3.214
> require(data.table)
> system.time(r <- fread("data")$V1)
   user  system elapsed 
  0.412   0.026   0.439 
Run Code Online (Sandbox Code Playgroud)

并验证:

> num <- as.numeric(readLines("data"))
> int <- as.integer(readLines("data"))
> sn <- scan("data",what=numeric())
Read 25000000 items
> si <- scan("data",what=integer())
Read 25000000 items
> dti <- fread("data")$V1
> identical(num,sn)
[1] TRUE
> identical(int,si)
[1] TRUE
> identical(int,dti)
[1] TRUE
Run Code Online (Sandbox Code Playgroud)