gpt4 book ai didi

R:循环处理大数据集(GB) block ?

转载 作者:行者123 更新时间:2023-12-04 17:22:38 27 4
gpt4 key购买 nike

我有一个以 GB 为单位的大数据集,我必须在分析它们之前对其进行处理。
我尝试创建一个连接器,它允许我遍历大型数据集并一次提取块。这允许我隔离满足某些条件的数据。

我的问题是我无法为连接器创建一个指标,规定它为空,并在到达数据集末尾时执行 close(connector)。此外,对于提取的第一块数据,我必须跳过 17 行,因为该文件包含 R 无法读取的 header 。

一个有效的手动尝试:

filename="nameoffile.txt"    
con<<-file(description=filename,open="r")
data<-read.table(con,nrows=1000,skip=17,header=FALSE)
data<-read.table(con,nrows=1000,skip=0,header=FALSE)
.
.
.
till end of dataset

由于我想避免在到达数据集末尾之前手动键入上述命令,因此我尝试编写一个循环来自动执行该过程,但未成功。

我尝试使用失败的循环:
filename="nameoffile.txt"    
con<<-file(description=filename,open="r")
data<-read.table(con,nrows=1000,skip=17,header=FALSE)
if (nrow(rval)==0) {
con <<-NULL
close(con)
}else{
if(nrow(rval)!=0){
con <<-file(description=filename, open="r")
data<-read.table(conn,nrows=1000,skip=0,header=FALSE)
}}

最佳答案

看起来你在正确的轨道上。只需打开连接一次(您不需要使用 <<- ,只需使用 <- ;使用更大的块大小,以便 R 的矢量化操作可以用于有效地处理每个块),沿着

filename <- "nameoffile.txt"
nrows <- 1000000
con <- file(description=filename,open="r")
## N.B.: skip = 17 from original prob.! Usually not needed (thx @Moody_Mudskipper)
data <- read.table(con, nrows=nrows, skip=17, header=FALSE)
repeat {
if (nrow(data) == 0)
break
## process chunk 'data' here, then...
## ...read next chunk
if (nrow(data) != nrows) # last chunk was final chunk
break
data <- tryCatch({
read.table(con, nrows=nrows, skip=0, header=FALSE)
}, error=function(err) {
## matching condition message only works when message is not translated
if (identical(conditionMessage(err), "no lines available in input"))
data.frame()
else stop(err)
})
}
close(con)

迭代在我看来是一个很好的策略,尤其是对于您将要处理一次而不是像数据库那样重复引用的文件。答案是 修改 尝试更稳健地检测文件末尾的读取。

关于R:循环处理大数据集(GB) block ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18564689/

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