fread 从一个大文件中读取前 n 行

fread to read top n rows from a large file

使用 fread 从一个大文件(大约 50 GB)中读取前 n 行时出现以下错误。看起来像内存问题。我尝试使用 nrows=1000 。但没有运气。使用 linux

file ok but could not memory map it. This is a 64bit process. There is probably not enough contiguous virtual memory available.

是否可以将下面的代码替换为 read.csv 以及下面使用的所有选项?有帮助吗?

  rdata<- fread(
      file=csvfile, sep= "|", header=FALSE, col.names= colsinfile,
    select= colstoselect, key = "keycolname", na.strings= c("", "NA")
    , nrows= 500
  )

也许这对你有帮助:

processFile = function(filepath) {
con = file(filepath, "r")
while ( TRUE ) {
line = readLines(con, n = 1)
if ( length(line) == 0 ) {
  break
}
print(line)
}
close(con)
}

参见reading a text file in R line by line.. 在您的情况下,您可能希望将 while ( TRUE ) 替换为 for(i in 1:1000)

另一种解决方法是使用 shell 命令获取前 500 行:

rdata<- fread(
    cmd = paste('head -n 500', csvfile),
    sep= "|", header=FALSE, col.names= colsinfile,
    select= colstoselect, key = "keycolname", na.strings= c("", "NA")
)

不过我不知道为什么 nrows 不起作用。