r - 尝试在 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
有没有办法运行我拥有的代码行但跳过不足的行?
解决方案
因为它在行上循环,我们可以做
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
推荐阅读
- java - ANTLR4 中基于目标的成员
- html - 并排调整列表项而不滚动
- swift - 带有 countDownTimer 的 UIDatePicker 显示“0 小时 2 分钟”
- java - 如何在 ALfresco 中创建父/子关系模型
- html - 我创建了一个 html 内容框,但它没有响应,我应该怎么做才能将它转换为响应?
- android - 如何将点击的项目传递给观察另一个值的视图模型?
- excel - 如何解决 Excel VBA:隐藏模块中的编译错误
- django - 嘿,为什么我不能在 django 中使用非主键字段进行 raq 查询,它没有找到这样的表
- android - 如何在markerview中显示超过5位
- java - 如何有效地查找数组中的重复元素?我的意思是说迭代次数非常少