Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate NAs in a vector using prior non-NA values?

Tags:

r

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

like image 344
SFun28 Avatar asked Jan 26 '12 18:01

SFun28


People also ask

How do I fill NAs in R?

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.

How do I replace missing values in NA with R?

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.

Which function is used to replace the NA values with the most recent values?

locf() function from the zoo package to carry the last observation forward to replace your NA values.

What is the opposite of NA in R?

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: !


1 Answers

library(zoo)
na.locf(test)
[1] 1 2 2 2 5 5 9 9 9
like image 119
Joshua Ulrich Avatar answered Oct 01 '22 01:10

Joshua Ulrich