title: How to interpolate missing values in a time series, limited by the number of sequential NAs (R)?
body: <p>I have missing values in a time series of dates. For example: </p>
  
  <pre><code>set.seed(101)
  
  df &lt;- data.frame(DATE = as.Date(c('2012-01-01', '2012-01-02', 
  '2012-01-03', '2012-01-05', '2012-01-06', '2012-01-15', '2012-01-18', 
  '2012-01-19', '2012-01-20', '2012-01-22')),
                   VALUE = rnorm(10, mean = 5, sd = 2))
  </code></pre>
  
  <p>How can I write a function that will fill all the missing dates between the first and last date (ie 2012-01-01 and 2012-01-22'), then use interpolation (linear and smoothing spline) to fill the missing values, but not more than 3 sequential missing values (ie no interpolation between 2012-01-06 and 2012-01-15)?</p>
  
  <p>The function will be applied to a very large dataframe. I have been able to write a function that uses linear interpolation to fill all missing values between two dates (see below), but I can not figure out how to stop it interpolating long stretches of missing values. </p>
  
  <pre><code>interpolate.V &lt;- function(df){
  
    # sort data by time 
    df &lt;- df[order(df$DATE),]
  
    # linnearly interpolate VALUE for all missing DATEs
    temp &lt;- with(df, data.frame(approx(DATE, VALUE, xout = seq(DATE[1], 
                 DATE[nrow(df)], "day"))))
    colnames(temp) &lt;- c("DATE", "VALUE_INTERPOLATED")
    temp$ST_ID &lt;- df$ST_ID[1]
    out &lt;- merge(df, temp, all = T)
    rm(temp)
  
    return(out)
  }
  </code></pre>
  
  <p>Any help will be greatly appreciated! </p>
  
  <p>Thanks</p>