Vectorize this for a loop (the current line depends on the line above)

Suppose I want to create n = 3 random walk paths (path length = 100), given the pre-generated matrix (100x3) plus / minus. The first path starts at 10, the second starts at 20, the third starts 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 final values ​​(taking into account the matrix of seeds and rands) are 14, 6, 34 ..., which is the desired result ... but ...

Question : Is there a way to vectorize a for loop? The problem is that when calculating the path matrix is ​​not yet completely filled. Thus, replacing the loop with path[2:101,]<-path[1:100,]+given.rand.matrix returns basically BUT. I just want to know if this type of for loop can be avoided in R.

.

+3
1

: 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
+6

Source: https://habr.com/ru/post/1787198/


All Articles