I have the following generator code for a random walk:
i = 1
t = 100
p = 0.5
max_walk = 1000
samples = rbinom(max_walk, 1, p)
samples[samples==0] = -1
walk = c(i, cumsum(samples))
In my case i is the value of the first step, and t would be the maximum value and zero the minimum. So my walk would have to stop when the value is less than or equal to zero or greater than or equal to t.
Is there any way to do this? Or maybe the cumsum doesn't add up when the respective result is less than or equal to zero or greater than or equal to t?
You can construct a loop using while()
, but it is simpler just to run your code as written and then identify the stop point:
stop <- which(walk < 1 | walk > max_walk)
stop[1] # First stop
# [1] 13
walk[stop[1]] # Value at first stop
# [1] 0
plot(walk, type="l") # Plot entire walk
points(stop[1], walk[stop[1]], col="red")