title: Using R to insert a value for missing data with a value from another data frame
body: <p>All,</p>
  
  <p>I have a question that I fear might be too pedestrian to ask here, but searching for it elsewhere is leading me astray. I may not be using the right search terms.</p>
  
  <p>I have a panel data frame (country-year) in R with some missing values on a given variable. I'm trying to impute them with the value from another vector in another data frame. Here's an illustration of what I am trying to do.</p>
  
  <p>Assume <code>Data</code> is the data frame of interest, which has missing values on a given vector that I'm trying to impute from another donor data frame. It looks like this.</p>
  
  <pre><code>country    year      x
    70       1920    9.234
    70       1921    9.234
    70       1922    9.234
    70       1923    9.234
    70       1924    9.234
    80       1920      NA
    80       1921      NA
    80       1922      NA
    80       1923      NA
    80       1924      NA
    90       1920    7.562
    90       1921    7.562
    90       1922    7.562
    90       1923    7.562
    90       1924    7.562
  </code></pre>
  
  <p>This would be the <code>Donor</code> frame, which has a value for <code>country == 80</code></p>
  
  <pre><code>country      x
    70       9.234
    80       1.523
    90       7.562
  </code></pre>
  
  <p>I'm trying to find a seamless way to automate this, beyond a command of <code>Data$x[Data$country == 80] &lt;- 1.523</code>. There are a lot of countries with missingness on <code>x</code>.</p>
  
  <p>It may be worth clarifying that a simple <code>merge</code> would be the easiest, but not necessarily appropriate for what I'm trying to do. Some countries will see variation on <code>x</code> over different years. Basically, what I'm trying to accomplish is a command that says that if the value of <code>x</code> is missing from <code>Data</code> for all years for a given country, take the corresponding value for the country from the <code>Donor</code> data and paste it over all country years as a "best guess" of sorts.</p>
  
  <p>Thanks for any input. I suspect this is a rookie question, but I didn't know the right terms to search for it. </p>
  
  <p>Reproducible code for the above data follows.</p>
  
  <pre><code>country &lt;- c(70,70,70,70,70,80,80,80,80,80,90,90,90,90,90)
  year &lt;- c(1920,1921,1922,1923,1924,1920,1921,1922,1923,1924,1920,1921,1922,1923,1924)
  x &lt;- c(9.234,9.234,9.234,9.234,9.234,NA,NA,NA,NA,NA,7.562,7.562,7.562,7.562,7.562)
  
  Data=data.frame(country=country,year=year,x=x)
  summary(Data)
  
  country &lt;- c(70,80,90)
  x &lt;- c(9.234,1.523,7.562)
  Donor=data.frame(country=country,x=x)
  summary(Donor)
  </code></pre>