使用`tryCatch`并在表达式失败时打印错误消息

Ind*_*til 1 error-handling r try-catch

我正在尝试编写一个自定义函数,该函数使用chisq.test(下面是它的玩具版本)执行拟合测试的优劣。我希望函数健壮,因此我要tryCatch确保如果指定了无效的概率向量,则函数将返回带有NaNs 的数据帧。

这是功能-

set.seed(123)

# custom function
custom_prop <- function(var, ratio) {
  tryCatch(
    expr = broom::tidy(stats::chisq.test(
      x = table(var),
      p = ratio
    )),
    error = function(x) {
      tibble::tribble(
        ~statistic, ~p.value, ~parameter,
        NaN, NaN, NaN
      )
    }
  )
}
Run Code Online (Sandbox Code Playgroud)

尝试有效的比率(向量总和为1;按预期工作)

custom_prop(mtcars$am, c(0.6, 0.4))
#> # A tibble: 1 x 4
#>   statistic p.value parameter method                                  
#>       <dbl>   <dbl>     <dbl> <chr>                                   
#> 1   0.00521   0.942         1 Chi-squared test for given probabilities

custom_prop(mtcars$am, c(0.7, 0.3))
#> # A tibble: 1 x 4
#>   statistic p.value parameter method                                  
#>       <dbl>   <dbl>     <dbl> <chr>                                   
#> 1      1.72   0.190         1 Chi-squared test for given probabilities
Run Code Online (Sandbox Code Playgroud)

尝试无效的比率(向量不等于1;按预期工作)

custom_prop(mtcars$am, c(0.6, 0.6))
#> # A tibble: 1 x 3
#>   statistic p.value parameter
#>       <dbl>   <dbl>     <dbl>
#> 1       NaN     NaN       NaN

custom_prop(mtcars$am, c(0.7, 0.5))
#> # A tibble: 1 x 3
#>   statistic p.value parameter
#>       <dbl>   <dbl>     <dbl>
#> 1       NaN     NaN       NaN
Run Code Online (Sandbox Code Playgroud)

但是这种方法的问题在于用户不知道该函数为什么不返回结果。如果我不使用tryCatch,他们会明白为什么-

broom::tidy(stats::chisq.test(
  x = table(mtcars$am),
  p = c(0.7,0.5)
))
#> Error in stats::chisq.test(x = table(mtcars$am), p = c(0.7, 0.5)): probabilities must sum to 1.
Run Code Online (Sandbox Code Playgroud)

我也尝试过这里提到的解决方案,但这只会返回NULL而不显示错误消息-

# custom function
custom_prop2 <- function(var, ratio) {
  tryCatch(
    expr = broom::tidy(stats::chisq.test(
      x = table(var),
      p = ratio
    )),
    error = function(e) {}
  )
}

# trying out invalid ratios
custom_prop2(mtcars$am, c(0.6, 0.6))
#> NULL
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是 -
有什么方法可以使用,tryCatch并且在表达式无法正常工作时打印错误消息?

nic*_*ola 5

只需使用错误消息来构建并抛出一个错误warning

custom_prop <- function(var, ratio) {
  tryCatch(
    expr = broom::tidy(stats::chisq.test(
      x = table(var),
      p = ratio
    )),
    error = function(x) {
      warning(x)   # just add this line
      tibble::tribble(
        ~statistic, ~p.value, ~parameter,
        NaN, NaN, NaN
      )
    }
  )
}

custom_prop(mtcars$am, c(0.6, 0.6))
# A tibble: 1 x 3
#  statistic p.value parameter
#      <dbl>   <dbl>     <dbl>
#1       NaN     NaN       NaN
#Warning message:
#In stats::chisq.test(x = table(var), p = ratio) :
#  probabilities must sum to 1.
Run Code Online (Sandbox Code Playgroud)