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.
.