tmp <- c(-1,NA,NA,1,1,NA,NA,1) without using a loop, how can I replace all NAs in the list above with the previous none NA value in the list?
On Tue, 7 Jun 2005 11:02:13 -0400 Omar Lakkis wrote:> tmp <- c(-1,NA,NA,1,1,NA,NA,1) > > without using a loop, how can I replace all NAs in the list above with > the previous none NA value in the list?Package zoo contains a generic function na.locf (last observation carried forward) which handles this: R> tmp <- c(-1,NA,NA,1,1,NA,NA,1) R> library(zoo) R> na.locf(tmp) [1] -1 -1 -1 1 1 1 1 1 Z> ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! > http://www.R-project.org/posting-guide.html >
How about the following: tmp <- c(-1,NA,NA,1,1,NA,NA,1) replaceNA <- function(x){ iNA <- which(is.na(x)) if(length(iNA) %in% c(0, length(x))) return(x) iNA1 <- iNA-1 iNA1[iNA==0] <- length(x) x[iNA] <- x[iNA1] replaceNA(x) } > replaceNA(tmp) [1] -1 -1 -1 1 1 1 1 1 > replaceNA(NA) [1] NA spencer graves Omar Lakkis wrote:> tmp <- c(-1,NA,NA,1,1,NA,NA,1) > > without using a loop, how can I replace all NAs in the list above with > the previous none NA value in the list? > > ______________________________________________ > R-help at stat.math.ethz.ch mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
On 6/7/05, Omar Lakkis <uofiowa at gmail.com> wrote:> tmp <- c(-1,NA,NA,1,1,NA,NA,1) > > without using a loop, how can I replace all NAs in the list above with > the previous none NA value in the list?This is known as last occurrence carried forward (LOCF) and is implemented in both the 'zoo' and 'its' packages, e.g. library(zoo) na.locf(tmp)