我在 R 中有一个非常大的数据文件(千兆),如果我尝试用 R 打开它,我会收到内存不足错误。
我需要逐行读取文件并进行一些分析。我发现了一个关于这个问题的上一个问题,其中文件是由 n 行读取并跳转到带有 clump 的某些行。我已经使用了“Nick Sabbe”的答案,并添加了一些修改以满足我的需要。
考虑我有以下 test.csv 文件样本:
A B C
200 19 0.1
400 18 0.1
300 29 0.1
800 88 0.1
600 80 0.1
150 50 0.1
190 33 0.1
270 42 0.1
900 73 0.1
730 95 0.1
我想逐行读取文件的内容并执行分析。因此,我创建了以下循环来根据“Nick Sabbe”发布的代码进行读取。我有两个问题:
1)每次打印新行时都会打印标题。
2)尽管我删除了该列,但 R 的索引“X”列也被打印。
这是我正在使用的代码:
test<-function(){
prev<-0
for(i in 1:100){
j<-i-prev
test1<-read.clump("file.csv",j,i)
print(test1)
prev<-i
}
}
####################
# Code by Nick Sabbe
###################
read.clump <- function(file, lines, clump, readFunc=read.csv,
skip=(lines*(clump-1))+ifelse((header) & (clump>1) & (!inherits(file, "connection")),1,0),
nrows=lines,header=TRUE,...){
if(clump > 1){
colnms<-NULL
if(header)
{
colnms<-unlist(readFunc(file, nrows=1, header=F))
#print(colnms)
}
p = readFunc(file, skip = skip,
nrows = nrows, header=FALSE,...)
if(! is.null(colnms))
{
colnames(p) = colnms
}
} else {
p = readFunc(file, skip = skip, nrows = nrows, header=header)
}
p$X<-NULL # Note: Here I'm setting the index to NULL
return(p)
}
我得到的输出:
A B C
1 200 19 0.1
NA 1 1 1
1 2 400 18 0.1
NA 1 1 1
1 3 300 29 0.1
NA 1 1 1
1 4 800 88 0.1
NA 1 1 1
1 5 600 80 0.1
我想在剩下的阅读中摆脱:
NA 1 1 1
另外,有什么方法可以让 for 循环在其他语言的文件结尾时停止,例如 EOF ???