fran
fran

Reputation: 43

Simulating a random walk in R

How do I simulate a sequence of random variables Xn with probability distribution P(Xn=1)=1/2, P(Xn=-1)=1/2 in R? (To be used to simulate a random walk).

Upvotes: 1

Views: 460

Answers (1)

deschen
deschen

Reputation: 10996

You could simply sample the desired number of elements:

n_decisions <- 100

set.seed(1)
random_walk <- sample(c(1, -1), size = n_decisions, replace = TRUE)

table(random_walk)

random_walk
-1  1 
51 49

cumsum(random_walk)

  [1]  1  0  1  2  1  2  3  4  3  2  3  4  5  6  7  6  5  4  3  4  5  6  7  8  9
 [26] 10  9 10 11 10  9  8  9  8  9 10  9 10  9  8  7  6  7  6  5  4  3  2  3  4
 [51]  3  4  3  2  3  4  3  2  1  2  3  2  1  0 -1 -2 -3 -2 -3 -4 -5 -6 -5 -4 -3
 [76] -4 -5 -4 -3 -4 -5 -6 -5 -4 -3 -4 -3 -4 -3 -4 -3 -2 -3 -4 -3 -2 -1 -2 -3 -2

enter image description here

Plot with N = 150.000

enter image description here

Upvotes: 2

Related Questions