0

I have the following code for a random walk, in which I start from i and add up cumulatively for each line.

However, I need to limit my random walk on each line. One way I thought of doing this, would be from the index j (where the value in the position is less than or equal to 0 or greater than or equal to t) of each line replace with null.

simulate_binomial = function(cenarios, rodadas, p){
  return(matrix(data=rbinom(cenarios*rodadas, 1, p), nrow=cenarios, ncol=rodadas))
}

i = 2
t = 10
p = 0.8

max_walk = 100

samples = simulate_binomial(1000, max_walk, p)

samples[samples==0] = -1

walk = t(apply(cbind(i, samples), 1, cumsum))
walk1 = apply(walk, 1, function(x) (which((x <= 0) | (x >= t))[1]))

So my walk1 would be the indices of each line that would have a value less than or equal to zero or greater than or equal to t. However, I don't know how to assign null for this index onwards in the line.

My intention is to assign null so that I can plot precisely without this null part and see the effect of the ruin on each line / "scenario".

Can anyone help me plz?

Eric Leung
  • 2,354
  • 12
  • 25

1 Answers1

1

You can change your last apply to :

walk1 <- t(apply(walk, 1, function(x) {
             inds <- (which((x <= 0) | (x >= t))[1])
             x[(inds+1):length(x)] <- NA
             x
          }))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213