title: Creating a function to replace NAs from one data.frame with values from another
body: <p>I regularly have situations where I need to replace missing values from a data.frame with values from some other data.frame that is at a different level of aggregation. So, for example, if I have a data.frame full of county data I might replace NA values with state values stored in another data.frame. After writing the same <code>merge</code>... <code>ifelse(is.na())</code> yada yada a few dozen times I decided to break down and write a function to do this. </p>
  
  <p>Here's what I cooked up, along with an example of how I use it:</p>
  
  <pre><code>fillNaDf &lt;- function(naDf, fillDf, mergeCols, fillCols){
   mergedDf &lt;- merge(naDf, fillDf, by=mergeCols)
   for (col in fillCols){
     colWithNas &lt;- mergedDf[[paste(col, "x", sep=".")]]
     colWithOutNas &lt;- mergedDf[[paste(col, "y", sep=".")]]
     k &lt;- which( is.na( colWithNas ) )
     colWithNas[k] &lt;- colWithOutNas[k]
     mergedDf[col] &lt;- colWithNas
     mergedDf[[paste(col, "x", sep=".")]] &lt;- NULL
     mergedDf[[paste(col, "y", sep=".")]] &lt;- NULL
   }
   return(mergedDf)
  }
  
  ## test case
  fillDf &lt;- data.frame(a = c(1,2,1,2), b = c(3,3,4,4) ,f = c(100,200, 300, 400), g = c(11, 12, 13, 14))
  naDf &lt;- data.frame( a = sample(c(1,2), 100, rep=TRUE), b = sample(c(3,4), 100, rep=TRUE), f = sample(c(0,NA), 100, rep=TRUE), g = sample(c(0,NA), 200, rep=TRUE) )
  fillNaDf(naDf, fillDf, mergeCols=c("a","b"), fillCols=c("f","g") )
  </code></pre>
  
  <p>So after I got this running I had this odd feeling that someone has probably solved this problem before me and in a much more elegant way. Is there a better/easier/faster solution to this problem? Also, is there a way that eliminates the loop in the middle of my function? That loop is there because I am often replacing NAs in more than one column. And, yes, the function assumes the columns we're filling <strong>from</strong> are named the same and the columns we are filling <strong>to</strong> and the same applies to the merge. </p>
  
  <p>Any guidance or refactoring would be helpful. </p>
  
  <p><em><strong>EDIT</em></strong> on Dec 2 I realized I had logic flaws in my example which I fixed. </p>