【问题标题】:quick way to read a large flat file into r as.numeric [duplicate]将大型平面文件读入 r as.numeric 的快速方法 [重复]
【发布时间】:2014-09-12 09:44:41
【问题描述】:

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

    1
    0
    0
    1
    0
    1
    0
    etc...

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

dat <- as.numeric(readLines("my_large_file"))

我得到了所需的数据结构,但需要很长时间。有什么更快的方法可以达到同样的效果吗?

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

【问题讨论】:

  • fread in data.table 非常擅长相对快速地读取大文件

标签: r bigdata flat-file


【解决方案1】:

对于只希望返回向量的数字文件,使用 scan 可能会做得更好。

scan("my_large_file", what = integer())

what 参数将进一步加快文件的读取速度(而不是将其排除在外),因为您实际上是在告诉 R 它将读取整数值。 scan 也有许多其他参数可以在大型数字文件中派上用场(例如 skipnlines 等)

此外,正如@baptiste 在 cmets 中提到的,

library(data.table)
fread("my_large_file")

readLinesscan 都吹走(在我的机器上)。

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

【讨论】:

  • 如果只是10,指定integer作为类型会更快,因为它们需要一半的内存而不是双倍的内存。
  • 明白了。谢谢你。
  • 谢谢@RichardScriven,fread 在几秒钟内完成了这项工作。
【解决方案2】:

比较几个选项的时间安排。首先,一些数据。

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

现在,一些基准测试(每个都从一个新的 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 

及验证:

> 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

【讨论】:

  • 谢谢,我刚刚从这个答案中学到了三个新东西。
  • @RichardScriven:我希望它们不仅是新的,而且是有用的。 ;)
  • 我觉得令人沮丧的是,一台计算机需要“一段时间”才能生成一个包含几百万个 0 和 1 的文本文件。
  • @baptiste: writecat 的包装器,它似乎没有针对这类事情进行优化。 writeLines 更快。
  • 其他东西似乎没有为此优化:过去 10 分钟我无法使用我的计算机,当我尝试生成黑白光栅图像时它冻结了具有该数量的像素。坏主意,下次我会用相机拍天空for randomness
猜你喜欢
  • 1970-01-01
  • 2021-03-23
  • 1970-01-01
  • 2013-02-03
  • 2017-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-26
相关资源
最近更新 更多