Q:

Replacing multiple NA's with one mean

I have a vector of the following type:
x <- c(2,5,1,5,NA,NA,NA,9,23,1,NA,NA,NA,5,2)
Is there a way to replace my NA's with the meanvalue of the value before and after the NA's? Like interpolating them, but with onyl one value!
*Update: expected output in this case would be c(2,5,1,5,7,7,7,9,23,1,3,3,3,5,2)
Thanks alot.

A:

We can use na.approx from zoo
library(zoo)
na.approx(x, method = "constant", f = .5)
# [1]  2  5  1  5  7  7  7  9 23  1  3  3  3  5  2

About the argument f, from ?approxfun

for method = "constant" a number between 0 and 1 inclusive, indicating a compromise between left- and right-continuous step functions. If y0 and y1 are the values to the left and right of the point then the value is y0 if f == 0, y1 if f == 1, and y0*(1-f)+y1*f for intermediate values. In this way the result is right-continuous for f == 0 and left-continuous for f == 1, even for non-finite y values

