[R] LOCF - Last Observation Carried Forward

Simon Fear Simon.Fear at synequanon.com
Fri Nov 14 17:28:03 CET 2003


I use this:

#
# change NAs to preceding values (initial NAs remain NAs)
# e.g.  NA  1 NA  2 NA NA  4 NA  3
# to    NA  1  1  2  2  2  4  4  3
"locf" <- function(x) {
  assign("stored.value", x[1], envir=.GlobalEnv)
  sapply(x, function(x) {
    if(is.na(x))
      stored.value
    else {
      assign("stored.value", x, envir=.GlobalEnv)
      x
    }})
}

That sets up "LOCF" within a vector, or could be applied to the
rows of your data frame:

df[ , <<numeric bits only>>] <- apply(df[ , <<numeric bits only>>], 2, locf)

I've got a feeling there would be a much neater way to code this
than the above (I wrote it first in Splus, hence the funny scoping control).

When  theres only one postbaseline timepoint, I tend to use this instead:

"set.nas.previous" <- function(x,previous) {
  if (is.numeric(x)) 
    x <- ifelse(is.na(x),previous,x)
  x
}

which is used like

df$locf <- set.nas.previous(df$postbaseline, df$baseline)

It's a bit of a dodgy function name really because there is no actual
test that "previous" is really previous.

HTH

Simon

PS use `subset` instead of `[`. Do what I say, not what I do.

> -----Original Message-----
> From: Karl Knoblick [mailto:karlknoblich at yahoo.de]
> Sent: 14 November 2003 14:08
> To: r-help at stat.math.ethz.ch
> Subject: [R] LOCF - Last Observation Carried Forward
> 
> 
> Security Warning: 
> If you are not sure an attachment is safe to open please contact  
> Andy on x234. There are 0 attachments with this message. 
> ________________________________________________________________ 
>  
> Hi!
>  
> Is there a possibilty in R to carry out LOCF (Last 
> Observation Carried Forward) analysis or to create a new data 
> frame (array, matrix) with LOCF? Or some helpful functions, packages?
>  
> Karl
> 
> 
> 
> ---------------------------------
> Gesendet von http://mail.yahoo.de
> Schneller als Mail - der neue Yahoo! Messenger.
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
>  
 
Simon Fear 
Senior Statistician 
Syne qua non Ltd 
Tel: +44 (0) 1379 644449 
Fax: +44 (0) 1379 644445 
email: Simon.Fear at synequanon.com 
web: http://www.synequanon.com 
  
Number of attachments included with this message: 0 
  
This message (and any associated files) is confidential and\...{{dropped}}




More information about the R-help mailing list