title: Replace value in a data.frame within a function (for use with apply)
body: <p>I have a data.frame that looks like this:</p>
  
  <pre><code>GROUP  |  YEAR  | VAL
  A      |  2007  | 10
  A      |  2007  | 11
  A      |  2007  | NA
  A      |  2008  | 13
  B      |  2006  | NA
  B      |  2006  | 5
  B      |  2006  | 6
  </code></pre>
  
  <p>So each group may have different years. I want to replace those NAs with the mean of the respective group in the respective year. For example, for the NA in row 3, it will be replaced by the mean of group A in year 2007.</p>
  
  <p>I can do this using a for loop, but unfortunately my professor has this hate for "for" loop, so I'm trying to find another way. I tried using a function like this:
  <code>imputeMean(group,year)</code>, it takes the group and year to calculate the mean, then mutate the data.frame. I then apply this function on a data.frame of group and year to be replaced.</p>
  
  <p>Unfortunately, R does not have pass-by-reference, which means I can't modify the original data.frame directly in the <code>imputeMean()</code> function. Is there anyway to calculate filter a data.frame, calculate the group mean with respect to year, and replace the NA value with this mean, without the use of loop?</p>