小编ada*_*ell的帖子

避免在R中循环

我想写一些关于编写更好的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]

  }
}
Run Code Online (Sandbox Code Playgroud)

看看发生了什么:

# 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
Run Code Online (Sandbox Code Playgroud)

optimization r vectorization

5
推荐指数
1
解决办法
158
查看次数

标签 统计

optimization ×1

r ×1

vectorization ×1