【问题标题】:Routing to another function if first function fails in R如果第一个函数在 R 中失败,则路由到另一个函数
【发布时间】:2019-02-08 14:51:47
【问题描述】:

我在 R 中调用一个函数

for(i in 1:nrow(ListA)){Produce_Output(ListA$ColumnA[i], ListA$ColumnB[i])} 

此函数根据最佳拟合生成 ETS 或 Auto.Arima 模型。但是,某些数据不允许使用此模型进行预测并带回错误(可以理解)。如果函数“Produce_Output”失败,我想要的是能够将变量 ColumnA 和 ColumnB 传递给另一个函数。

我可以使用“尝试”来忽略错误,但这不是我想要的。查看 TryCatch 函数,这出现(可能)到我需要查看的区域,但是我只能看到有关如何返回句柄而不是传递以激活另一个函数的参考。

【问题讨论】:

    标签: r exception error-handling try-catch


    【解决方案1】:

    试试这个语法(更新为可重现的例子:)

    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
    

    使用apply() 示例避免for循环:

    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
    

    【讨论】:

    • 如果我去掉 another_function(ListA$ColumnA[i], ListA$ColumnB[i]),第一部分就可以工作,如果我不这样做,它似乎只是挂起,这可能表明一个循环,但是我不确定它是如何循环的
    • 我更新了一个可重现的示例,也许是您正在使用的函数中的某些东西导致它挂起?
    猜你喜欢
    • 1970-01-01
    • 2014-07-14
    • 2017-03-31
    • 2021-06-25
    • 2020-02-01
    • 2022-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多