【问题标题】:R try catch blockR尝试捕获块
【发布时间】:2014-11-25 13:47:56
【问题描述】:

我正在尝试循环评估树的多个输出参数。但有时树函数会中止。行如何被 try catch 块包围?

对于没有“真实”代码,我深表歉意,但我没有非工作树的示例。这是pseddo代码来说明当前的实现

for (icol in seq(1,ncol)) {
  cName <-colnames(dt)[icol]
  tdata <- dt[,unique(c(1,2,icol)),with=F]
  nTrues <- sum(rowSums(tdata[,cName,with=F]))
  if (nTrues>0 ) {
    print(paste('processing column',icol,'of',ncol,': ',cName))
    nFac <- table(tdata[,cName,with=F])
    print(nFac)
    treeData <- merge(tdata, maint_data)
    treeData[,c('identifiers'):=NULL]
    fmla <- paste(cName,'~ .')
    if (TRUE) {
      # Recursive Partitioning and Regression Trees
      cat('Recursive Partitioning and Regression Trees (rpart)','\n')
      rtree <- rpart(fmla,data=treeData)  # <-- NEED TRY CATCH HERE...
      print(summary(rtree))
      cat('Confusion matrix for rpart')
      print(table(predict(rtree), treeData[[cName]]))
    }
    flush.console()
  } else {
    print(paste('skipping column',icol,'of',ncol(ci_ratio_before_larger),': ',cName))
  }
}

这是一个似乎有效的更正......

  tryCatch({
    # Recursive Partitioning and Regression Trees
    cat('Recursive Partitioning and Regression Trees (rpart)','\n')
    rtree <- rpart(fmla,data=treeData)
    print(summary(rtree))
    cat('Confusion matrix for rpart')
    print(table(predict(rtree,type='vector'), treeData[[cName]]))
  },
  error = function (condition) {
    print("RPART_ERROR:")
    print(paste("  Message:",conditionMessage(condition)))
    print(paste("  Call: ",conditionCall(condition)))
  }
  )

【问题讨论】:

  • 在错误处理程序中,使用接口conditionMessage(condition)conditionCall(call),而不是依赖这些S3类的结构。
  • 我相信你的意思是 conditionCall(condition),但我同意。

标签: r tree try-catch


【解决方案1】:

我无法真正测试它,但你可以尝试更换你的

if (TRUE)

条件:

tryCatch({
  # Recursive Partitioning and Regression Trees
  cat('Recursive Partitioning and Regression Trees (rpart)','\n')
  rtree <- rpart(fmla,data=treeData)  # <-- NEED TRY CATCH HERE...
  print(summary(rtree))
  cat('Confusion matrix for rpart')
  print(table(predict(rtree), treeData[[cName]]))
},
error = function (condition) {
  print("RPART_ERROR:")
  print(paste("  Message:",conditionMessage(condition)))
  print(paste("  Call: ",conditionCall(condition)))
},
finally= function() {

}
)

【讨论】:

  • 我在循环之前有一个接收器,用于捕获文件中的输出。如何在条件中捕获错误消息。我将 write("Error",stderr()) 替换为 message(condition),但消息没有写入文件。
  • 啊,抱歉,我在编辑答案后看到了您的评论。您可以删除接收器部分,并且仅在出现错误时将消息添加到文件中吗?或者这会破坏你的输出?
  • 我必须查看条件的结构才能打印它。我用“答案”更新了问题,现在已经足够了......
  • 感谢您的更新。我也会更新我的答案,至少是可执行的。
  • 您能否更新您的答案以合并接口函数调用,见上文。
猜你喜欢
  • 2011-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-27
  • 2020-07-31
  • 2017-04-14
相关资源
最近更新 更多