In fact, the imputeTS package (I am a developer) offers good solutions for this.
Moving Average Replacement
na.ma(x, k = 2)
x - your input object k - moving average window
k of 1 means that you only consider the values before and after k of 2 means that you count 2 values before and 2 values after
This function is probably closest to the required calculation. The only difference is that the imputeTS method does not jump over the NA values. (as required by the starter thread)
But especially for long NA bands, this makes sense. 1, 2, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 14, 15, 16 (taking the average of 2 and 14 for NA at position 3 would be nice)
Also Last Observation Forward (as noted in comment 42)
imputeTS::na.locf(x)
or Interpolation (also mentioned by G. Grothendieck)
imputeTS::na.interpolation(x)
There are also no data replacement options that go a bit in one direction. The following is an introduction to the imputeTS package in R Journal if you are interested.
stats0007
source share