title: How do I calculate means of time series data with different time horizons and NAs in R
body: <p>I have two dataframes. One with relevant time horizons (in years) of observations and one with time series data of these observations.
  The time horizons differ for every observation. Moreover, data is not available for every year in the given time horizons.
  I want to calculate the mean of the time series data for every observation time horizon's available data.
  Additionally, I need to know from when on data is available for every observation.</p>
  <p>So if these two data frames are given:</p>
  <pre><code>
  time_horizon &lt;- data.frame(observation = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;), 
                             start = c(2010, 2011, 2012), 
                             end = c(2015, 2016, 2015)
                             )
  
  data &lt;- data.frame(Year = c(2010:2016), 
                     A = c(NA, NA, 19485, 19485, 19456, 19454, 18475), 
                     B = c(NA, NA, NA, 18762, 18567, 18321, 19001), 
                     C = c(26374, 21134, 21212, 21111, 21344, 22222, 21345)
                     )
  
  </code></pre>
  <p>I need a data frame like this as a result:</p>
  <pre><code>calculated &lt;- data.frame(observation = c(&quot;A&quot;, &quot;B&quot;, &quot;C&quot;),
                           mean = c(19470, 18662.75, 21472.25),
                           data_start = c(2012, 2013, 2015),
                           data_end = c(2015, 2016, 2015)
                           )
  
  </code></pre>
  <p>I have tried several variations of colMeans(x, na.rm = TRUE) or apply(x,2,mean, na.rm = TRUE) but I could not come up with a solution that takes the varying time horizons into account. Also for the ex post indication of the available data time horizons I have no solution.</p>
  <p>Any suggestions?</p>