首页 > 解决方案 > 如何跳过和忽略循环中无法被一行代码读取或提供错误的行?

问题描述

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 等。

标签: rloopstry-catch

解决方案


我不确定我是否完全遵循您的代码/数据,但是如果您将 tryCatch 语句移动到 apply 语句中,像这样:apply(df, 2, function(x) tryCatch(tidy(chisq.test(matrix(x, ncol = 2))))) %>% bind_rows?这些帮助有用?


推荐阅读