Skip to content
Prev 298902 / 398513 Next

using "na.locf" from package zoo to fill NA gaps

On Mon, Jul 2, 2012 at 11:17 AM, jeff6868
<geoffrey_klein at etu.u-bourgogne.fr> wrote:
Try doing it forwards and backwards and only replacing if they are the same:

library(zoo)

na.locf.ifeq <- function(x) {
	ix <- na.locf(x) == na.locf(x, fromLast = TRUE) & is.na(x)
	replace(x, ix, na.locf(x)[ix])
}

# test 1
x1 <- c(1, 2, 3, NA, NA, NA, 6, 7, 8, 9)
na.locf.ifeq(x1)

# test 2
x2 <- c(1, 2, 3, NA, NA, NA, 3, 4, 5, 6)
na.locf.ifeq(x2)