3

Suppose I want to create n=3 random walk paths (pathlength = 100) given a pre-generated matrix (100x3) of plus/minus ones. The first path will start at 10, the second at 20, the third at 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,]
}

The end values (given the seed and rand matrix) are 14, 6, 34... which is the desired result... but...

Question: Is there a way to vectorize the for loop? The problem is that the path matrix is not yet fully populated when calculating. Thus, replacing the loop with path[2:101,]<-path[1:100,]+given.rand.matrix returns mostly NAs. I just want to know if this type of for loop is avoidable in R.

Thank you very much in advance.

4

1 回答 1

6

Definitely vectorizable: Skip the initialization of path, and use cumsum over the matrix:

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
于 2011-01-22T22:15:11.363 回答