vector for this for循环(当前行取决于上面的行)

时间:2011-01-22 21:17:41

标签: r vectorization

假设我想在给定预生成的正/负1矩阵(100x3)的情况下创建n = 3个随机游走路径(pathlength = 100)。第一条路径从10开始,第二条路径从20开始,第三条路径从30开始:

set.seed(123)
given.rand.matrix <- replicate(3,sign(rnorm(100)))
path <- matrix(NA,101,3)
path[1,] = c(10,20,30)

for (j in 2:101) {
  path[j,]<-path[j-1,]+given.rand.matrix[j-1,]
}

结束值(给定种子和兰特矩阵)是14,6,34 ......这是期望的结果......但是......

问题:有没有办法对for循环进行矢量化?问题是计算时路径矩阵尚未完全填充。因此,用。替换循环 path[2:101,]<-path[1:100,]+given.rand.matrix 主要返回NAs。我只是想知道这种类型的for循环在R中是否可以避免。

非常感谢你。

1 个答案:

答案 0 :(得分:6)

绝对可矢量化:跳过path的初始化,并在矩阵上使用cumsum

path <- apply( rbind(c(10,20,30),given.rand.matrix), 2, cumsum)

> head(path)
     [,1] [,2] [,3]
[1,]   10   20   30
[2,]    9   19   31
[3,]    8   20   32
[4,]    9   19   31
[5,]   10   18   32
[6,]   11   17   31
> tail(path)
       [,1] [,2] [,3]
[96,]    15    7   31
[97,]    14    8   32
[98,]    15    9   33
[99,]    16    8   32
[100,]   15    7   33
[101,]   14    6   34