0

I am trying to replace all the zeros with the previous number from a list.

The list is something like this:

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

I tried already the function

x <- c(3,0,0,0,0,1,0,0,0,0,0,2,0,0,0,0,3,0,0,0,1,0,2,0)
replace (x, x==0, first(x))
[1] 3 3 3 3 3 1 3 3 3 3 3 2 3 3 3 3 3 3 3 3 1 3 2 3

But it changes the first value of the list =3 to all the zeros and the 2's and 1's are neglected.

Also

replace (x, x==0, x)
[1] 3 3 0 0 0 1 0 1 0 0 0 2 0 0 2 0 3 0 0 0 1 3 2 0
A. Suliman
  • 12,923
  • 5
  • 24
  • 37
Astrid
  • 15
  • 3

2 Answers2

1

You can use approx after you replaced all zeros with NA

approx(replace(x, x == 0, NA),
       xout = 1:length(x), method = "constant", f = 0, rule = 2)$y
# [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 1 1 2 2
markus
  • 25,843
  • 5
  • 39
  • 58
1

Could modify this.

fill = function(x){
    ave(x, cumsum(x != 0), FUN = function(y) y[pmax(1, cumsum(y != 0))])
}
fill(x)
# [1] 3 3 3 3 3 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 1 1 2 2
d.b
  • 32,245
  • 6
  • 36
  • 77