-1

我正在使用 for 循环对我的数据的特定子集执行操作。在 for 循环的每次迭代结束时,我拥有填充数据框行所需的所有值。

到目前为止我试过

df=NULL
for(...){  
//stuff to calculate   
newline=c(allthethingscalculated)  
df=rbind(df,newline)
}

这导致无法使用 '$' 访问数据帧的内容,因为这些行是原子向量。

我还尝试将在每次迭代结束时获得的值附加到已经存在的向量中,当 for 循环结束时,使用从这些向量创建数据帧,但将值附加到相应的向量不起作用,值不是添加。

x<-data.frame(a,b,c,d,...)

对此有什么想法吗?


由于我的 for 循环遍历数据中的 ID,我意识到我可以执行以下操作:

uids=unique(data$id)
filler=c(1:length(uids))
df=data.frame(uids,filler,filler,filler,filler,filler,filler,filler,filler,filler)

for(i in uids){
...
df[i,]<-newline
}

我使用填充器创建了一个具有正确列数和行数的数据框,所以我不会收到类似“替换长度为 9,替换长度为 1”之类的错误

有一个更好的方法吗?使用这种方法,我仍然需要删除相应行中的填充值?

4

1 回答 1

0

这应该可行,您可以向我们展示您的数据吗?

R) x=data.frame(a=rep(1,3),b=rep(2,3),c=rep(3,3))
R) d=c(4,4,4)
R) rbind(x,d)
  a b c
1 1 2 3
2 1 2 3
3 1 2 3
4 4 4 4
R) cbind(x,d)
  a b c d
1 1 2 3 4
2 1 2 3 4
3 1 2 3 4
于 2013-03-19T07:46:40.227 回答