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.
Using R replace() function to update 0 with NA R has a built-in function called replace() that replaces values in a vector with another value, for example, zeros with NAs.
To replace a column value in R use square bracket notation df[] , By using this you can update values on a single column or on all columns. To refer to a single column use df$column_name .
Replace NA values with 0 using is.na() In this way, we can replace NA values with Zero(0) in an R DataFrame.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With