Search code examples
rloopsconditional-statementsapplymapply

How do I replace a value taking into account the previous value from a list in R?


I am trying to replace all the ones values after zero with zero values.

The list is something like this:

x <- c(1,1,0,1,1,1,1,1,0,1,1)

I want the output to be like this:

c(1,1,0,0,1,1,1,1,0,0,1)

So, the next value after 0 are also 0.

I have done it with loops but because it´s a large amount of information is a lot of time to wait. I hope someone could give me an idea.


Solution

  • x[ c(FALSE, x[-length(x)] == 0) ] <- 0
    x
    #  [1] 1 1 0 0 1 1 1 1 0 0 1
    identical(
      x,
      c(1,1,0,0,1,1,1,1,0,0,1) # from the OP
    )
    # [1] TRUE