r - 如何跳过和忽略循环中无法被一行代码读取或提供错误的行?
问题描述
structure(list(`total primary - yes RS` = c(0L, 138L, 101L, 86L,
118L), `total primary - no RS` = c(0L, 29L, 39L, 35L, 38L), `total secondary- yes rs` = c(0L,
6L, 15L, 3L, 15L), `total secondary- no rs` = c(0L, 0L, 7L, 1L,
2L)), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))
我之前曾要求提供一行代码,可以为包含的四行中的每一行运行一个卡方
https://stackoverflow.com/questions/66750999/with-r-i-would-like-to-loop-through-each-row-and-create-corresponding-chisquare/66751018#66751018
虽然脚本有效,但它只是有效,因为四行能够通过脚本运行。
library(broom)
library(dplyr)
apply(df, 1, function(x) tidy(chisq.test(matrix(x, ncol = 2)))) %>%
bind_rows
我现在有一条为零的行,当我运行相同的脚本时,我得到了
Error in stats::chisq.test(x, y, ...) :
at least one entry of 'x' must be positive
我试着用 tryCatch() 做一些事情,这样
tryCatch(apply(df, 1, function(x) tidy(chisq.test(matrix(x, ncol = 2))))) %>%
bind_rows
但它没有用。最终数据集有一堆像这样的行我想要一个脚本识别它不仅在第 1 行,而且在多行中,如 5、23、67 等。
解决方案
我不确定我是否完全遵循您的代码/数据,但是如果您将 tryCatch 语句移动到 apply 语句中,像这样:apply(df, 2, function(x) tryCatch(tidy(chisq.test(matrix(x, ncol = 2))))) %>% bind_rows
?这些帮助有用?
推荐阅读
- wpf - TabControl 视图不会在模板更改时更新
- ansible - Ansible:使用 regexp 和 backrefs 的 lineinfile 模块
- sql - 如何编写 SQL 查询来更改顺序并截断 JSON 有效负载中的元素?
- python - 如何在 Tkinter 中将 Notebook 选项卡分为两个部分?
- authentication - 尝试在 Drupal 7 中访问未发布的内容页面时如何将用户重定向到登录页面
- regex - 如何选择具有一定间隔的所有空格
- cloud-foundry - HTML5 应用程序 (Cloud Foundry) - 404 Not Found nginx
- redirect - IIS 重定向 多个域允许一个访问文件夹 - 拒绝访问另一个
- python - 如何将 mpmath 和 sympy 添加到 buildozer 要求中
- r - 如何使用设备进行并行绘图?