[英]How to combine tryCatch and If-Else statements in R?
目的
我有數百本 Excel 練習冊。 其中大多數都有一張紙,比如“正確的紙”。 這些工作表都應該有 10 列。 我想將它們全部組合成一個統一的數據集(最終數據集)。
但是,某些工作簿沒有正確的工作表,加載它們時出現錯誤。 我確實有正確的工作表,其中一些沒有 10 列。 我想排除任何沒有正確工作表或正確工作表沒有 10 列的工作簿。
試圖
假設正確的工作表是一個數值變量。 因此,在下面的兩個變量中,只有“b”是正確的,因為它具有數值。 a = "你好" b = 8
代表
a <- "hello"
b <- 8
#A: Check that a + 2 does not produce an error
if(tryCatch({a + 2}, error = function(e) {"error"}) != "error") {
#A1:If a+2 does not produce an error, then check that the sum is right
if(a+2 == 10) {
print("a No error and produced correct answer - Add 'a' to consolidated list")
} else {
#B: Check that b + 2 does not produce an error
if(tryCatch({b+2}, error = function(e) {"error"}) != "error") {
#B1:If b+2 does not produce an error, then check that the sum is right
if(b+2 == 10) {
print("a No error but produced wrong answer,
b No error and produced correct answer,
Add 'b' to consolidated list")
} else {
print("a No error but produced wrong answer, b No error but produced wrong answer")
}
#B2: If b+2 produced an error
} else {print("a No error but produced wrong answer, b Error")}
}
#A2:If a+2 produces an error, then go straight to b
} else {
#B: Check that b + 2 does not produce an error
if(tryCatch({b+2}, error = function(e) {"error"}) != "error") {
#B1:If b+2 does not produce an error, then check that the sum is right
if(b+2 == 10) {
print("a Error,
b No error and produced correct answer,
Add 'b' to consolidated list")
} else {
print("a Error, b No error but produced wrong answer")
}
#B2: If b+2 produced an error
} else {print("a Error, b Error")}
}
問題
我實際上有三個變量(例如 a =“你好”,b = 8 和 c =“再見”,這增加了上述復雜性。
有更簡單的方法嗎?
您可以嘗試purrr::safely()
。 下面是一個使用“Excel 工作簿”嵌套列表的模擬示例:
library(purrr)
# example "workbooks"
wkbks <- list(
w1 = list(
sheet1 = 1:3,
`Correct Sheet` = 1:10
),
w2 = list(
sheet1 = 1:3
),
w3 = list(
`Correct Sheet` = 1:8
),
w4 = list(
`Correct Sheet` = 1:10,
sheet2 = 1:5
)
)
# helper function to read wkbk and throw error conditions not met
read_correct <- function(x) {
stopifnot(length(x[["Correct Sheet"]]) == 10)
x[["Correct Sheet"]]
}
# iterate over wkbks, wrapping `read_correct` in `safely()`
correct_sheets <- wkbks |>
map(safely(read_correct)) |>
transpose()
結果:
# see all errors, removing NULLs
#> compact(correct_sheets$error)
$w2
<simpleError in .f(...): length(x[["Correct Sheet"]]) == 10 is not TRUE>
$w3
<simpleError in .f(...): length(x[["Correct Sheet"]]) == 10 is not TRUE>
# see all correct results, removing NULLs
#> compact(correct_sheets$result)
$w1
[1] 1 2 3 4 5 6 7 8 9 10
$w4
[1] 1 2 3 4 5 6 7 8 9 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.