R replacing zeros in the data frame with the last nonzero value

I have a dataframe with a column containing null values:

a <- c(1:10)
b <- c(1,0,0,0,0,-1,-1,0,0,1)
df <-data.frame(a,b)
df

How to replace null values ​​with the last nonzero value, i.e. df $ b column:

 1,-1,-1,-1,-1,-1,-1,1,1,1

Thank you for your help.

+4
source share
1 answer

Here is one way na.locffrom zoo. Although this method changes some values ​​to NAin the process, the code is nice and painless.

library(zoo)
na.locf(with(df, ifelse(b == 0, NA_real_, b)), fromLast = TRUE)
# [1]  1 -1 -1 -1 -1 -1 -1  1  1  1

An alternative to this and faster than ifelsefor long vectors is

na.locf(with(df, { is.na(b) <- b == 0; b }), fromLast = TRUE)
# [1]  1 -1 -1 -1 -1 -1 -1  1  1  1
+7
source

All Articles