我想要一些关于编写更好的 R 代码的建议。我目前在 R 中编写了一个循环,但它存在性能问题。
我无法集中精力对其进行矢量化,因为输出数据帧中的每一行都依赖于较早的行,并且它们会迭代地向下流动,因此我编写了一个循环来按顺序读/写行。
我的代码示例:
example <- data.frame(a=c(.5,.1,.5,.25),b=c(1,0,2,0),c=c(1,2,3,4),d=c(4,3,2,1))
for (i in 2:nrow(example)) {
if (example[i,1]>0) {
example[i,2]<-example[i,2]+example[i-1,2]*example[i,1]
example[i,3]<-example[i,3]+example[i-1,3]*example[i,1]
example[i,4]<-example[i,4]+example[i-1,4]*example[i,1]
}
}
要查看发生了什么:
# before
a b c d
1 0.50 1 1 4
2 0.10 0 2 3
3 0.50 2 3 2
4 0.25 0 4 1
# after
a b c d
1 0.50 1.0000 1.0000 4.000
2 0.10 0.1000 2.1000 3.400
3 0.50 2.0500 4.0500 3.700
4 0.25 0.5125 5.0125 1.925