Function na.approx refuses character

I would just like to interpolate by using the "constant" method but character seems not to be supported by approx function what could I do.

  na.approx(c('a', NA, NA,'b', NA, NA,'a', NA, NA, NA, NA), 
            maxgap = 3,
            method = "constant")
  # should return : c('a', 'a', 'a','b', 'b', 'b','a', NA, NA, NA, NA)

Instead it gives the error message:

Error in approx(x[!na], y[!na], xout, ...) : zero non-NA points

1 answer

  • answered 2018-04-17 06:08 mt1022


    You should use na.locf:

    na.locf(x, maxgap = 3, na.rm = FALSE)
     [1] "a" "a" "a" "b" "b" "b" "a" NA  NA  NA  NA 

    Original answer

    na.approx only accept numeric vectors. But you can do this manually:

    na.approx.char.con <- function(x, maxgap){
        ave(x, cumsum(!, FUN = function(x){
            if(length(x) > maxgap + 1){
                rep(x[1], length(x))
    x <- c('a', NA, NA,'b', NA, NA,'a', NA, NA, NA, NA)
    na.approx.char.con(x, maxgap = 3)
    # [1] "a" "a" "a" "b" "b" "b" "a" NA  NA  NA  NA