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

使用“tryCatch”并在表达式失败时打印错误消息,r,error-handling,try-catch,R,Error Handling,Try Catch,我正在尝试编写一个自定义函数,它使用chisq.test执行拟合优度测试(下面是它的一个玩具版本)。我希望函数是健壮的,因此我使用tryCatch来确保如果指定了无效的概率向量,函数返回一个带有NaNs的数据帧 下面是函数- set.seed(123) #自定义函数 定制道具:1 x 4 #>统计p值参数法 #> #>1 0.00521 0.942 1给定概率的卡方检验 定制道具(mtcars$

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

下面是函数-

set.seed(123)
#自定义函数
定制道具:1 x 4
#>统计p值参数法
#>                                                   
#>1 0.00521 0.942 1给定概率的卡方检验
定制道具(mtcars$am,c(0.7,0.3))
#>#A tibble:1 x 4
#>统计p值参数法
#>                                                   
#>1 1.72 0.190 1给定概率的卡方检验
尝试无效比率(向量和不等于1;按预期工作)

定制道具(mtcars$am,c(0.6,0.6))
#>#A tible:1 x 3
#>统计p值参数
#>               
#>1楠楠楠楠楠楠
定制道具(mtcars$am,c(0.7,0.5))
#>#A tible:1 x 3
#>统计p值参数
#>               
#>1楠楠楠楠楠楠
但是这种方法的问题是用户不知道函数为什么不返回结果。如果我不使用
tryCatch
,他们会知道原因-

broom::tidy(stats::chisq.test)(
x=表(mtcars$am),
p=c(0.7,0.5)
))
#>统计中的错误::chisq.test(x=表(mtcars$am),p=c(0.7,0.5)):概率总和必须为1。
我还尝试了上面提到的解决方案,但它只返回NULL而不打印错误消息-

#自定义函数
自定义属性2 NULL
所以,我的问题是-

当表达式无法工作时,是否有任何方法可以使用
tryCatch
打印错误消息?

只需使用错误消息生成并抛出
警告即可:

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.

custom_prop只需使用错误消息构建并抛出一个
警告

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.

custom\u prop必须在错误块中打印
x
(或传入匿名函数的任何变量)。必须在错误块中打印
x
(或传入匿名函数的任何变量)。