微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

尝试在 R 的应用函数中使用 tryCatch

如何解决尝试在 R 的应用函数中使用 tryCatch

数据集是

 structure(list(`total primary - yes RS` = c(0L,1L,0L,138L,101L),`total primary - no RS` = c(0L,29L,39L),`total secondary- yes rs` = c(0L,6L,15L),`total secondary- no rs` = c(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)))) %>%

bind_rows

虽然此脚本有效,但我收到一条错误消息,内容

at least one entry of 'x' must be positive

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

解决方法

当它在行上循环时,我们可以做

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。