Here an example of my dataframe:
df = read.table(text = 'a b
120 5
120 5
120 5
119 0
118 0
88 3
88 3
87 0
10 3
10 3
10 3
7 4
6 0
5 0
4 0', header = TRUE)
I need to replace the 0s within col b
with each preceding number diverse than 0.
Here my desired output:
a b
120 5
120 5
120 5
119 5
118 5
88 3
88 3
87 3
10 3
10 3
10 3
7 4
6 4
5 4
4 4
Until now I tried:
df$b[df$b == 0] = (df$b == 0) - 1
But it does not work. Thanks
cum*
functions could be worth some tries. E.g. heredf$b[cummax((df$b > 0) * (1:nrow(df)))]
seems to be correct. – Famous