读取大文件中的前n行

时间:2018-09-25 07:39:25

标签: r data.table fread

使用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
  )

2 个答案:

答案 0 :(得分:1)

也许这会帮助您:

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)

答案 1 :(得分:1)

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

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

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

相关问题