TryCatch循环-R

时间:2018-10-30 16:00:42

标签: r try-catch

我的初始循环如下:

 for(iRow in seq(1,nrow(df),1)){


valueTMP <- df$Set_C[iRow]
strikeTMP <- df$`Exercise price`[iRow]
underlyingTMP <- df$Compens.[iRow]
dividendyieldTMP <- df$RFR[iRow]
riskfreerateTMP <- df$RFR[iRow]
maturityTMP <- df$maturity[iRow]


  df$IV[iRow] <- AmericanOptionImpliedVolatility("call", valueTMP, underlyingTMP, strikeTMP,dividendyieldTMP, riskfreerateTMP, maturityTMP, 0.4)

  }

此循环返回直到特定行的值。我想使用TryCatch,因此尝试了以下操作。但是,它不会改变以前的结果。我认为代码中缺少某些内容,即使在出现错误消息后,它也会返回某些内容。

for(iRow in seq(1,nrow(df),1)){


 valueTMP <- df$Set_C[iRow]
 strikeTMP <- df$`Exercise price`[iRow]
 underlyingTMP <- df$Compens.[iRow]
 dividendyieldTMP <- df$RFR[iRow]
 riskfreerateTMP <- df$RFR[iRow]
 maturityTMP <- df$maturity[iRow]


#ERROR HANDLING
possibleError <- tryCatch(
  thing(),
  error=function(e) e
)

    if(inherits(possibleError, "error")) next
  df$IV[iRow] <- AmericanOptionImpliedVolatility("call", valueTMP, 
underlyingTMP, strikeTMP, dividendyieldTMP, riskfreerateTMP, maturityTMP, 0.4)

  }

有人会知道如何使它直到最后一次观察才起作用,即使对于某些行它不会运行? 非常感谢。

1 个答案:

答案 0 :(得分:0)

这行得通,尽管需要花费很多时间:

 for(iRow in seq(1,nrow(df),1)){


valueTMP <- df$Set_P[iRow]
strikeTMP <- df$`Exercise price`[iRow]
underlyingTMP <- df$Compens.[iRow]
dividendyieldTMP <- df$RFR[iRow]
riskfreerateTMP <- df$RFR[iRow]
maturityTMP <- df$maturity[iRow]


try(  df$IV[iRow] <- AmericanOptionImpliedVolatility("put", valueTMP, underlyingTMP, 
strikeTMP,dividendyieldTMP, riskfreerateTMP,  maturityTMP, 0.4))
if (inherits(df$IV, "try-error")) next

  }