title: How to fill NAs with LOCF by factors in data frame, split by country
body: <p>I have the following data frame (simplified) with the country variable as a factor and the value variable has missing values:</p>
  
  <pre><code>country value
  AUT     NA
  AUT     5
  AUT     NA
  AUT     NA
  GER     NA
  GER     NA
  GER     7
  GER     NA
  GER     NA
  </code></pre>
  
  <p>The following generates the above data frame:</p>
  
  <pre><code>data &lt;- data.frame(country=c("AUT", "AUT", "AUT", "AUT", "GER", "GER", "GER", "GER", "GER"), value=c(NA, 5, NA, NA, NA, NA, 7, NA, NA))
  </code></pre>
  
  <p>Now, I would like to replace the NA values in each country subset using the method last observation carried forward (LOCF). I know the command <code>na.locf</code> in the <strong>zoo</strong> package. <code>data &lt;- na.locf(data)</code> would give me the following data frame:</p>
  
  <pre><code>country value
  AUT     NA
  AUT     5
  AUT     5
  AUT     5
  GER     5
  GER     5
  GER     7
  GER     7
  GER     7
  </code></pre>
  
  <p>However, <strong><em>the function should only be used on the individual subsets split by the country</em></strong>. The following is the output I would need:</p>
  
  <pre><code>country value
  AUT     NA
  AUT     5
  AUT     5
  AUT     5
  GER     NA
  GER     NA
  GER     7
  GER     7
  GER     7
  </code></pre>
  
  <p>I can't think of an easy way to implement it. Before starting with for-loops, I was wondering if anyone has any idea as to how to solve this.</p>
  
  <p>Many thanks!!</p>