Here I have a data that looks like this:
year <- c(2000,2001,2002,2003,2005,2006,2007,2008,2009,2010)
x <- c(1,2,3,NA,5,NA,NA,NA,9,10)
dat <- data.frame(year, x)
- I want to replace
NAwith the nearest neighbor according to the year variable.
For example, The fourth place of the data (the first NA) takes the value from its left neighbor rather than its right neighbor because its year "2003" is closer to "2002" instead of "2005"
- I want to leave the
NAthere when it does not have nearest nonNA neighbor.
For example, the seventh place of the data (the third NA) will still be NA because it does not have non-NA neighbor.
After imputing, the resulting x should be 1, 2, 3, 3, 5, 5, NA, 9, 9, 10