r assign nearest available value to NA -


instead loop, there short , efficient way assign nearest available value na in column in dataframe? e.g, there's dataframe df

df <- data.frame(x = c(1:10), y1 = c(0, 10, na,5, 20,30,7,8,9,11), y2 = c(na, 0, na,5, 20,30,7,8,na,na), z = c(95,94,90:87,88,89,90,91))      x y1 y2  z 1   1  0 na 95 2   2 10  0 94 3   3 na na 90 4   4  5  5 89 5   5 20 20 88 6   6 30 30 87 7   7  7  7 88 8   8  8  8 89 9   9  9 na 90 10 10 11 na 91 

and final df should be

    x y1 y2  z 1   1  0  0 95 2   2 10  0 94 3   3 10  0 90 4   4  5  5 89 5   5 20 20 88 6   6 30 30 87 7   7  7  7 88 8   8  8  8 89 9   9  9  8 90 10 10 11  8 91 

thanks in advance!

try

library(zoo) na.locf(na.locf(df), fromlast = true) 

Comments