title: Replace NA with mean of values in previous and following row in R
body: <p>I've got this data.frame full of NA's. </p>
  
  <pre><code>DATE &lt;- c("1","2","3","4","5","6","7","1","2","3","4","5","6","7")
  COMP &lt;- c("A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "B", "B", "B")
  BM &lt;- c(12,11,NA,14,NA,15,NA, 5, 5, NA, 6, NA, 8, 9)
  df &lt;- data.frame(DATE, COMP, BM, stringsAsFactors=F)
  
  df
  
  #    DATE COMP BM
  # 1     1    A 12
  # 2     2    A 11
  # 3     3    A NA
  # 4     4    A 14
  # 5     5    A NA
  # 6     6    A 15
  # 7     7    A NA
  # 8     1    B  5
  # 9     2    B  5
  # 10    3    B NA
  # 11    4    B  6
  # 12    5    B NA
  # 13    6    B  8
  # 14    7    B  9
  </code></pre>
  
  <p>I want to replace those NA's with the mean of the values in the previous and following row (only if it's the same company of course). If the first row is NA, the following row's value should be taken, if the last row is NA, the second last row's value should be taken. </p>
  
  <p>The output should look like this</p>
  
  <pre><code>#    DATE COMP BM
  # 1     1    A 12
  # 2     2    A 11
  # 3     3    A 12.5
  # 4     4    A 14
  # 5     5    A 14.5
  # 6     6    A 15
  # 7     7    A 15
  # 8     1    B  5
  # 9     2    B  5
  # 10    3    B  5.5
  # 11    4    B  6
  # 12    5    B  7
  # 13    6    B  8
  # 14    7    B  9
  </code></pre>
  
  <p>Thank you!</p>