【问题标题】:can I read a file consecutively without rewinding to the beginning in R?我可以连续读取文件而不倒回到R中的开头吗?
【发布时间】:2013-12-23 01:00:01
【问题描述】:

各位专家,

我正在尝试以 10000 行的连续块读取一个大文件。这是 因为文件太大,无法一次读入。 read.csv 的“跳过”字段进来
方便完成这项任务(见下文)。但是我注意到程序启动了 在文件末尾放慢速度(对于较大的 i 值)。 我怀疑这是因为每次调用 read.csv(file,skip=nskip,nrows=block) 总是 从头开始读取文件,直到所需的起始行“skip”为 到达。随着 i 的增加,这变得越来越耗时。 问题:有没有办法从最后一个位置开始继续读取文件 在上一个区块到达?

    numberOfBlocksInFile<-800
    block<-10000
for ( i in 1:(n-1))
{

            print(i)
    nskip<-i*block

    out<-read.csv(file,skip=nskip,nrows=block)
    colnames(out)<-names

            .....
            print("keep going")

    }

many thanks (:-

【问题讨论】:

  • 你见过this postthis post吗?
  • 连接可以以这种方式运行,但 read.csv 甚至 read.table 和 scan 会在终止时关闭它们的连接。我在 ?seek 的帮助页面中发现这条评论很有趣:“不鼓励在 Windows 上使用 seek。我们在 Windows 文件定位实现中发现了很多错误,建议用户仅在自担风险使用它,并要求不要用关于 Windows 缺陷的错误报告来浪费 R 开发人员的时间。”
  • @DWin read.csv 只关闭它打开的连接,所以先打开它,如图here
  • 对不起。我无法以您说明的方式进行连续读取。一次读取后,连接被报告为“无效”。

标签: r


【解决方案1】:

一种方法是将readLines 与文件连接一起使用。例如,您可以这样做:

temp.fpath <- tempfile() # create a temp file for this demo
d <- data.frame(a=letters[1:10], b=1:10) # sample data, 10 rows. we'll read 5 at a time
write.csv(d, temp.fpath, row.names=FALSE) # write the sample data
f.cnxn <- file(temp.fpath, 'r') # open a new connection

fields <- readLines(f.cnxn, n=1) # read the header, which we'll reuse for each block
block.size <- 5

repeat { # keep reading and printing 5 row chunks until you reach the end of the cnxn.
    block.text <- readLines(f.cnxn, n=5) # read chunk
    if (length(block.text) == 0) # if there's nothing left, leave the loop
        break

    block <- read.csv(text=c(fields, block.text)) # process chunk with
    print(block)
}

close(f.cnxn)
file.remove(temp.fpath)

【讨论】:

    【解决方案2】:

    另一种选择是使用来自read.table 包的fread

    N <- 1e6   ##  1 second to read 1e6 rows/10cols
    skip <- N
    DT <- fread("test.csv",nrows=N)
    repeat {
      if (nrow(DT) < N) break
      DT <- fread("test.csv",nrows=N,skip=skip)
      ## here use DT for your process
      skip <- skip + N
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多