如何提高R中读取二进制文件的速度

时间:2017-09-12 09:00:23

标签: r binary data.table

我必须将相当大的二进制文件读入R(处理,转换,转换为其他格式)。一般来说,我的方法运行正常但不幸的是,脚本永远运行(对于数据的第一部分,> 12小时,小于所有数据的2%)。

我强烈认为问题不是真正由于数据的大小(至少不是唯一的解释),而是由于代码效率低下。我正在寻找一种加速运行时间的方法,非常感谢任何帮助!

我的方法主要基于本教程:https://stats.idre.ucla.edu/r/faq/how-can-i-read-binary-data-into-r/

在下面的代码中,我只包含两个变量,而不是数千个变量。总的来说,数据是~100GB,但如上所述,即使处理第一部分(<2%)也需要> 12h。

数据已经分成较小的文件,我单独处理(对于每个第一部分脚本和一个数据集)。

我的代码:

newdata = file(paste0(getwd(), "/file.dat"), "rb")

# here, only first two variables
dataset <- data.table(ID = integer(),
                  v1 = integer())

# 327639 is the number of cases (data on people)
for(i in 1:327639) {
  bla <- readBin(con = newdata, integer(), size = 2, n=2000, endian = "big")
  ID <- i
  v1 = bla[1]

  dataset <- rbind(dataset, list(ID, v1))
}
save(dataset, file = paste0(getwd(), "/Output/", "Part_a.RData"))
close(newdata)

感谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

也许这是完全错误的,如果是这样,请原谅噪音 我在评论中的想法可以实现如下。 (未经测试,没有数据文件。)

#numbytes <- file.size(newdata)
numbytes <- 327639L

dataset <- data.table(ID = integer(numbytes),
                  v1 = integer(numbytes))

chunk <- 2^15
passes <- numbytes %/% chunk
remainder <- numbytes %% chunk

i <- 1L
for(j in seq_len(passes)){
    bla <- readBin(con = newdata, integer(), n = chunk, size = 2, endian = "big")
    dataset$ID[i:(i + chunk - 1L)] <- i:(i + chunk - 1L)
    dataset$vl[i:(i + chunk - 1L)] <- bla
    i <- i + chunk
}
bla <- readBin(con = newdata, integer(), n = remainder, size = 2, endian = "big")
dataset$ID[i:numbytes] <- i:numbytes
dataset$vl[i:numbytes] <- bla
相关问题