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.

  library(zoo)     
  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 05:55 mt1022

    Edit

    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(!is.na(x)), FUN = function(x){
            if(length(x) > maxgap + 1){
                x
            }else{
                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