Home > Back-end >  How do I replace a value taking into account the previous value from a list in R?
How do I replace a value taking into account the previous value from a list in R?

Time:12-10

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.

CodePudding user response:

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

CodePudding user response:

You could do:

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

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