title: replace NA with mean of column groups
body: <p>I want to find the means of all values in groups of columns.  A given group of columns might contain missing observations.  I want to replace the missing observations within a group of columns by the mean for that group of columns.  In my case the number of columns per group is a constant, <code>years</code>.</p>
  
  <p>Below is code that does this.  However, I am hoping someone might provide code that is much more efficient.  The <code>lapply</code> finds the mean for a given group of columns.  However, I have not yet come up with a similar approach for replacing the missing observations.  Thank you for any advice.</p>
  
  <p>Here is an example data set:</p>
  
  <pre><code>my.first.year &lt;- 1980
  my.last.year  &lt;- 1982
  years &lt;- (my.last.year - my.first.year) + 1
  
  x = read.table(text = "
   city county   state      a80    a81    a82    b80     b81   b82
    1      B       AA        2      20    200     4       8     12
    2      B       AA        4      NA    400     5       9     NA
    1      C       AA        6      60     NA    NA      10     14
    2      C       AA       NA      80    800     7      11     15    
  ", sep = "", header = TRUE, stringsAsFactors = FALSE)
  
  (2 + 4 + 6 + 20 + 60 + 80 + 200 + 400 + 800) / 9
  (4 + 5 + 7 + 8 + 9 + 10 + 11 + 12 + 14 + 15) / 10
  
  my.means &lt;- lapply( seq(4, ncol(x), years) , function(i) { mean(unlist(x[,i : (i+years-1) ]) , na.rm=TRUE) } )
  my.means
  
  x2 &lt;- x
  
  x2[,(3+years*0+1):(3+years*1)][is.na(x2[,(3+years*0+1):(3+years*1)])] = my.means[[1]]
  x2[,(3+years*1+1):(3+years*2)][is.na(x2[,(3+years*1+1):(3+years*2)])] = my.means[[2]]
  </code></pre>
  
  <p>Here is the result:</p>
  
  <pre><code>#   city county state      a80      a81      a82 b80 b81  b82
  # 1    1      B    AA   2.0000  20.0000 200.0000 4.0   8 12.0
  # 2    2      B    AA   4.0000 174.6667 400.0000 5.0   9  9.5
  # 3    1      C    AA   6.0000  60.0000 174.6667 9.5  10 14.0
  # 4    2      C    AA 174.6667  80.0000 800.0000 7.0  11 15.0
  </code></pre>