尝试在 R 的应用函数中使用 tryCatch
Attempt to use tryCatch in an apply function in R
数据集是
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"
))
然后从数据集 i 运行 中得到每一行的卡方。虽然这在这里正常工作,但不是因为一些值包含零。
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
数据集是
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"
))
然后从数据集 i 运行 中得到每一行的卡方。虽然这在这里正常工作,但不是因为一些值包含零。
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