R splinefun with NA

Asked

Viewed 30 times

3

Has anyone used splinefun with a set of data with NA?

x<-c(0.7948801, 1.3248001, 1.5897601, 8.7436794, 9.5385607, 12.4531202, 13.2480008, 14.0428786, 23.0515214, 23.5814400, 28.3507206, 31.0003216, 31.7951981, 34.7097597, 34.9747231, 37.0944000, 38.4191978, 39.2140825, 40.8038409, 44.5132790, 46.3679953, 52.9920087, 59.0860789, 60.1459215, 60.6758428, 113.9327984, 122.1465702, 142.8134403)

y<-c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA)

interpolar <- function(x, y)
{
    f <- splinefun(x, y, method = "hyman", ties=mean)#0.5142539###0.5157599
    qq <- mean(x)
    y_qq <- f(qq)
    N <- length(x)*10
    X1 <- seq(min(x), max(x), length.out = N)
    res <- list(horiz = y_qq, vert = qq)
    invisible(res)
}

teste<-as.numeric(interpolar(x,y))[1]
    Error in splinefun(x, y, method = "hyman", ties = mean) : 
      zero non-NA points

All right, if he’s NA, let that appear as a "test" answer. The only thing I need is for him to make no mistake and lock the entire loop. (In case someone asks, I have no way to improve the y, my data doesn’t really exist).

1 answer

3


Can use tryCatch to catch code execution errors and then act on the result. I also created an auxiliary function, is.error, to test the output of splinefun.

is.error <- function(x) inherits(x, "error")

interpolar <- function(x, y){
  f <- tryCatch(splinefun(x, y, method = "hyman", ties=mean),
                error = function(e) e)
  if(is.error(f)){
    res <- f
  }else{
    qq <- mean(x)
    y_qq <- f(qq)
    N <- length(x)*10
    X1 <- seq(min(x), max(x), length.out = N)
    res <- list(horiz = y_qq, vert = qq)
  }
  invisible(res)
}

teste <- interpolar(x, y)
if(is.error(teste)){
  print(teste$message)
}else{
  teste <- as.numeric(teste)[1]
}
#[1] "zero non-NA points"

A perhaps simpler to use version may be as follows. In this case the auxiliary function is not required. The function interpolar2 has an extra argument, err.message, to decide whether or not the error message is printed. By default err.message = TRUE. This can be changed to FALSE, if you want.

interpolar2 <- function(x, y, err.message = TRUE){
  f <- tryCatch(splinefun(x, y, method = "hyman", ties=mean),
                error = function(e) e)
  if(inherits(f, "error")){
    if(err.message) print(f)
    if(grepl("NA", f$message)){
      res <- NA
    }else{
      res <- NULL
    }
  }else{
    qq <- mean(x)
    y_qq <- f(qq)
    N <- length(x)*10
    X1 <- seq(min(x), max(x), length.out = N)
    res <- list(horiz = y_qq, vert = qq)
  }
  invisible(res)
}

teste2a <- as.numeric(interpolar2(x, y))[1]
#<simpleError in splinefun(x, y, method = "hyman", ties = mean): zero non-NA points>
teste2a
#[1] NA

teste2b <- as.numeric(interpolar2(x, y, FALSE))[1]
teste2b
#[1] NA

Browser other questions tagged

You are not signed in. Login or sign up in order to post.