How to repeat 1000 times this random simulation of a walk in R?

I simulate a one-dimensional and symmetric random walk procedure:

y[t] = y[t-1] + epsilon[t] 

where white noise is denoted by epsilon[t] ~ N(0,1) for the period t . There is no drift in this procedure.

In addition, RW is symmetric because Pr(y[i] = +1) = Pr(y[i] = -1) = 0.5 .

Here is my code in R:

 set.seed(1) t=1000 epsilon=sample(c(-1,1), t, replace = 1) y<-c() y[1]<-0 for (i in 2:t) { y[i]<-y[i-1]+epsilon[i] } par(mfrow=c(1,2)) plot(1:t, y, type="l", main="Random walk") outcomes <- sapply(1:1000, function(i) cumsum(y[i])) hist(outcomes) 

I would like to simulate 1000 different series y[i,t] ( i=1,...,1000; t=1,...,1000 ). (After that, I will check the probability of returning to the origin ( y[1]=0 ) at t=3 , t=5 and t=10 )

What function would allow me to do such repetitions with y[t] random walk time series?

+5
source share
1 answer

Since y[t] = y[0] + sum epsilon[i] , where sum is taken from i=1 to i=t , the sequence y[t] can be calculated immediately using, for example, the function R cumsum . Repeating a series of T = 10ยณ times is simple:

 N=T=1e3 y=t(apply(matrix(sample(c(-1,1),N*T,rep=TRUE),ncol=T),1,cumsum)) 

since each row y is then a simulated sequence of random walks.

+6
source

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


All Articles