Попробуйте этот синтаксис (обновлен до воспроизводимого примера:)
ListA <- data.frame(ColumnA = c(1,2,3,4),
ColumnB = c("a","b","c","d"),
stringsAsFactors = FALSE)
Produce_Output <- function(i,j){
if(i %in% c(2,4)){
stop("Error in Produce Output")
}
cat(" \n# Produce Output: ", i, j)
}
another_function <- function(i,j){
cat("\n#another function:", i, j)
}
for(i in 1:nrow(ListA)){
tryCatch(
Produce_Output(ListA$ColumnA[i], ListA$ColumnB[i]),
error = function(ex){
warning("Had an error - ", ex)
another_function(ListA$ColumnA[i], ListA$ColumnB[i])
})
}
Который производит этот вывод:
# Produce Output: 1 a
# another_function: 2 b
# Produce Output: 3 c
# another_function: 4 dWarning messages:
1: In value[[3L]](cond) :
Had an error - Error in Produce_Output(ListA$ColumnA[i], ListA$ColumnB[i]): Error in Produce Output
2: In value[[3L]](cond) :
Had an error - Error in Produce_Output(ListA$ColumnA[i], ListA$ColumnB[i]): Error in Produce Output
Как избежать цикла for, используя apply()
пример:
f <- function(x){
tryCatch(
Produce_Output(x[["ColumnA"]], x[["ColumnB"]]),
error = function(ex){
warning("Had an error - ", ex)
another_function(x[["ColumnA"]], x[["ColumnB"]])
})
}
out <- apply(ListA, 1, f)
# Produce Output: 1 a
# another_function: 2 b
# Produce Output: 3 c
# another_function: 4 dWarning messages:
1: In value[[3L]](cond) :
Had an error - Error in Produce_Output(ListA$ColumnA[i], ListA$ColumnB[i]): Error in Produce Output
2: In value[[3L]](cond) :
Had an error - Error in Produce_Output(ListA$ColumnA[i], ListA$ColumnB[i]): Error in Produce Output