首页 > 解决方案 > 尝试在 R 的应用函数中使用 tryCatch

问题描述

数据集是

 structure(list(`total primary - yes RS` = c(0L, 1L, 0L, 138L, 
101L), `total primary - no RS` = c(0L, 0L, 0L, 29L, 39L), `total secondary- yes rs` = c(0L, 
0L, 0L, 6L, 15L), `total secondary- no rs` = c(0L, 0L, 0L, 0L, 
7L)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))

然后从数据集中我运行它以获得每行的卡方。虽然这在这里正常工作,但它不是因为一些值包含零。

yes<-apply(sample, 1, function(x) tidy(chisq.test(matrix(x, ncol = 2)))) %>%

绑定行

虽然这个脚本有效,但我收到一条错误消息,上面写着

at least one entry of 'x' must be positive

有没有办法运行我拥有的代码行但跳过不足的行?

标签: rapplychi-squared

解决方案


因为它在行上循环,我们可以做

out <- apply(sample, 1, function(x) tryCatch(tidy(chisq.test(matrix(x, 
       ncol = 2))), error = function(err) tibble(statistic = NA)))



dplyr::bind_rows(out)
# A tibble: 5 x 4
#  statistic p.value parameter method                                                      
#      <dbl>   <dbl>     <int> <chr>                                                       
#1   NA       NA            NA <NA>                                                        
#2  NaN      NaN             1 Pearson's Chi-squared test                                  
#3   NA       NA            NA <NA>                                                        
#4    0.317    0.574         1 Pearson's Chi-squared test with Yates' continuity correction
#5    0.0166   0.898         1 Pearson's Chi-squared test with Yates' continuity correction

推荐阅读