You could also use the na.approx
function from the zoo
package. Note that this has a slightly different behavior (than the solution by @flodel) when you have two consecutive NA
values. For the first and last row you could then use na.locf
.
y <- na.approx(x)
y[nrow(y), ] <- na.locf(y[(nrow(y)-1):nrow(y), ])[2, ]
y[1, ] <- na.locf(y[1:2,], fromLast=TRUE)[1, ]
EDIT: @Grothendieck pointed out that this was much too complicated. You can combine the entire code above into one line:
na.approx(x, rule=2)