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

Viewed 51

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.

2 Answers
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

You could do:

x[which(x == 0) + 1] <- 0

 [1] 1 1 0 0 1 1 1 1 0 0 1
Related