What's a compact/efficient way to populate NAs using the prior non-NA value? For example:
test = c( 1 , 2 , NA , NA , 5 , NA , 9 , NA , NA )
expected = c( 1 , 2 , 2 , 2 , 5 , 5 , 9 , 9 , 9 )
Here, all of the NA values 'look back' to the first non-NA value. I'm trying to avoid a for loop
To replace NA with 0 in an R data frame, use is.na() function and then select all those values with NA and assign them to 0.
So, how do you replace missing values with basic R code? To replace the missing values, you first identify the NA's with the is.na() function and the $-operator. Then, you use the min() function to replace the NA's with the lowest value.
locf() function from the zoo package to carry the last observation forward to replace your NA values.
An important feature of is.na is that the function can be reversed by simply putting a ! (exclamation mark) in front. In this case, TRUE indicates a value that is not NA in R: !
library(zoo)
na.locf(test)
[1] 1 2 2 2 5 5 9 9 9
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