1

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

user438383
  • 5,716
  • 8
  • 28
  • 43
fran
  • 43
  • 4

1 Answers1

2

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

deschen
  • 10,012
  • 3
  • 27
  • 50