我想将大数据表流式传输到R LINE BY LINE,如果当前行具有特定条件(假设第一列> 15),则将该行添加到内存中的数据帧。我写了以下代码:
count<-1;
Mydata<-NULL;
fin <- FALSE;
while (!fin){
if (count==1){
Myrow=read.delim(pipe('cat /dev/stdin'), header=F,sep="\t",nrows=1);
Mydata<-rbind(Mydata,Myrow);
count<-count+1;
}
else {
count<-count+1;
Myrow=read.delim(pipe('cat /dev/stdin'), header=F,sep="\t",nrows=1);
if (Myrow!=""){
if (MyCONDITION){
Mydata<-rbind(Mydata,Myrow);
}
}
else
{fin<-TRUE}
}
}
print(Mydata);
但我收到错误“数据不可用”。 请注意我的数据很大,我不想一次性阅读并应用我的条件(在这种情况下很容易)。
答案 0 :(得分:12)
我认为使用像readLines
这样的R函数会更明智。 readLines
仅支持读取指定数量的行,例如1.将其与首先打开file
连接相结合,然后反复调用readLines
获取您想要的内容。多次调用readLines
时,将从连接中读取下一行n
行。在R代码中:
stop = FALSE
f = file("/tmp/test.txt", "r")
while(!stop) {
next_line = readLines(f, n = 1)
## Insert some if statement logic here
if(length(next_line) == 0) {
stop = TRUE
close(f)
}
}
补充意见:
stdin()
。我建议您使用此而不是使用pipe('cat /dev/stdin')
。这可能使它更加强大,而且绝对更具跨平台性。Mydata
并使用rbind
继续增长rbind
。如果MyData
变大的行数,这将变得非常慢。这与这样一个事实有关:当对象增长时,操作系统需要为它找到一个新的内存位置,最终需要很多的时间。更好的方法是预先分配{{1}},或使用apply style loops。