Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm simulating 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) in time period t. There is no drift in this procedure.

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

Here's 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 y[i,t] series (i=1,...,1000; t=1,...,1000). (After that, I will check the probability of getting back to the origin (y[1]=0) at t=3, t=5 and t=10.)

Which function would allow me to do this kind of repetition with y[t] random walk time-series?

like image 955
Übel Yildmar Avatar asked Feb 21 '16 10:02

Übel Yildmar


People also ask

How do you simulate a random walk in R?

The function use rnorm() to generate random normal variable, and then use cumsum() to get the random walk. Note that the whole function is based on vector operation, instead of looping over time.

How do I simulate a dataset in R?

Introduction: Simulating data This can be accomplished with base R functions including rnorm , runif , rbinom , rpois , or rgamma ; all of these functions sample univariate data (i.e., one variable) from a specified distribution.

What is R In simulation?

The “r” function is the one that actually simulates randon numbers from that distribution. The other functions are prefixed with a. d for density. r for random number generation. p for cumulative distribution.


1 Answers

Since y[t] = y[0] + sum epsilon[i], where the sum is taken from i=1 to i=t, the sequence y[t] can be computed at once, using for instance R cumsum function. Repeating the series T=10³ times is then straightforward:

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

since each row of y is then a simulated random walk series.

like image 180
Xi'an Avatar answered Oct 16 '22 17:10

Xi'an