5

I have a dataframe with a column containing zero values:

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

How can I replace the zero values with the last non zero value ie column df$b to be:

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

Thank you for your help.

0

1 Answer 1

8

Here's one way with na.locf from zoo. Although this method does change some values to NA in 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 one that might be faster than ifelse on 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
1
  • 2
    And another variation: na.locf(with(df, replace(b,b==0,NA)), fromLast = TRUE) Oct 20, 2014 at 0:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.