Replace rows with 0s in dataframe with preceding row values diverse than 0

conditional-statements, dataframe, r, replace, rows

Solution

`na.locf` from `zoo` can help with this:

library(zoo)
#converting zeros to NA so that na.locf can get them
df$b[df$b == 0] <- NA
#using na.locf to replace NA with previous value
df$b <- na.locf(df$b)

Out:

> df
     a b
1  120 5
2  120 5
3  120 5
4  119 5
5  118 5
6   88 3
7   88 3
8   87 3
9   10 3
10  10 3
11  10 3
12   7 4
13   6 4
14   5 4
15   4 4

Problem

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

Original source