Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R replacing zeros in dataframe with next non zero value

Tags:

replace

r

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.

like image 263
adam.888 Avatar asked Oct 16 '14 21:10

adam.888


People also ask

How do I replace 0 with NA in R of a column?

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.

How do you substitute values in R?

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 .

How do I replace values with 0 in R?

Replace NA values with 0 using is.na() In this way, we can replace NA values with Zero(0) in an R DataFrame.


1 Answers

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
like image 111
Rich Scriven Avatar answered Sep 22 '22 05:09

Rich Scriven