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

我完全不熟悉在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

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

转载请注明出处:http://www.hjsszs.com/article/20230526/1904870.html