title: Last Observation Carried Forward In a data frame?
body: <p>I wish to implement a &quot;Last Observation Carried Forward&quot; for a data set I am working on which has missing values at the end of it.</p>
  <p>Here is a simple code to do it (question after it):</p>
  <pre><code>LOCF &lt;- function(x)
  {
      # Last Observation Carried Forward (for a left to right series)
      LOCF &lt;- max(which(!is.na(x))) # the location of the Last Observation to Carry Forward
      x[LOCF:length(x)] &lt;- x[LOCF]
      return(x)
  }
  
  
  # example:
  LOCF(c(1,2,3,4,NA,NA))
  LOCF(c(1,NA,3,4,NA,NA))
  </code></pre>
  <p>Now this works great for simple vectors. But if I where to try and use it on a data frame:</p>
  <pre><code>a &lt;- data.frame(rep(&quot;a&quot;,4), 1:4,1:4, c(1,NA,NA,NA))
  a
  t(apply(a, 1, LOCF)) # will make a mess
  </code></pre>
  <p>It will turn my data frame into a character matrix.</p>
  <p>Can you think of a way to do LOCF on a data.frame, without turning it into a matrix? (I could use loops and such to correct the mess, but would love for a more elegant solution)</p>