gpt4 book ai didi

r - 我可以连续读取文件而不倒回到 R 中的开头吗?

转载 作者:行者123 更新时间:2023-12-04 11:17:48 24 4
gpt4 key购买 nike

各位专家,

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

    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 (:-

最佳答案

一种方法是将 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)

关于r - 我可以连续读取文件而不倒回到 R 中的开头吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20410979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com