R语言如何正确使用try函数忽略循环执行后出现的任意报错
R中搭配循环使用try忽略错误的正确写法
你原有try写法未生效的核心原因是:默认try会打印报错信息,且如果把try包裹在整个循环外部,循环内任意步骤报错会直接终止整个循环块的执行,仅跳过整个块。根据你的需求可以选择两种适配写法:
场景1:整块代码报错就完全跳过,不执行块内剩余逻辑
直接在原有try调用中添加silent = TRUE参数即可,捕获错误后静默跳过整个块,直接执行后续脚本:
try( { # 用大括号包裹整块逻辑,结构更清晰 if (sum(staff[, 2] == 2) > 1) { for (i in d_wrk) { A[cur.row, which(shed.matrix[, 3] == i & shed.matrix[, 2] == 1)] <- 1 cur.row <- cur.row + 1 } B[cur.pos:(cur.pos + 6 - cnt_d_off)] <- 1 dirs[cur.pos:(cur.pos + 6 - cnt_d_off)] <- '>=' cur.pos <- cur.pos + 7 - cnt_d_off } }, silent = TRUE # 静默捕获错误,不打印报错信息 )
场景2:仅跳过循环中报错的单轮迭代,剩余循环继续执行
需要把try包裹在for循环的内部,每一轮迭代单独捕获错误:
if (sum(staff[, 2] == 2) > 1) { for (i in d_wrk) { try( { A[cur.row, which(shed.matrix[, 3] == i & shed.matrix[, 2] == 1)] <- 1 cur.row <- cur.row + 1 }, silent = TRUE ) } # 循环外的逻辑如果也需要忽略错误,同样可以单独包try try({ B[cur.pos:(cur.pos + 6 - cnt_d_off)] <- 1 dirs[cur.pos:(cur.pos + 6 - cnt_d_off)] <- '>=' cur.pos <- cur.pos + 7 - cnt_d_off }, silent = TRUE) }
如果需要对错误做分类处理,可以替换为tryCatch,仅需忽略报错的话上述try写法已经满足需求。
内容的提问来源于stack exchange,提问作者psysky
相关产品推荐
相关产品推荐

