R中的tryCatch:处理非数字向量

时间:2016-07-13 13:44:09

标签: r

我在R中使用tryCatch是全新的。这是我的代码:

# Outputs outliers

outlier <- function(vector){

  #error handling if vector can't be converted to numeric vector
  vector <- tryCatch(expr = as.numeric(vector),
                     error = {message("The vector is not numeric.")
                              return(NULL)})

  #calculate IQR (i.e., Q_3 - Q_1)
  IQR <- diff(quantile(vector, probs = c(0.25, 0.75), names = FALSE))

  #calculate lower fence and upper fence
  LF <- quantile(vector, probs = 0.25, names = FALSE) - 1.5 * IQR
  UF <- quantile(vector, probs = 0.75, names = FALSE) + 1.5 * IQR

  #find values of vector which are either less than the lower fence
  #or greater than the upper fence of data.

  return(vector[which(vector < LF | vector > UF)])

}

例如,

> outlier(c(-25, 0, 1, 2))
The vector is not numeric.
NULL

这显然不应该发生。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您需要将错误消息包装到函数中:

vector <- tryCatch(expr = as.numeric(vector),
                   warning = function(w) {
                       message("The vector is not numeric.")
                       return(NULL)
                   })

应该工作。