R尝试捕获块 [英] R try catch block

查看:28
本文介绍了R尝试捕获块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to evaluate trees for a number of output parameters, in a loop. But sometimes the tree function aborts. How can the lines be surrounded by a try catch block?

我很抱歉没有真正的"代码,但我没有非工作树的示例.下面是 pseddo 代码来说明当前的实现

I apologize for not having "real" code, but I don't have an example of a non working tree. Here's pseddo code to illustrate the current implementation

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))
  }
}

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

Here's a correction that seems to work....

  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)))
  }
  )

推荐答案

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

I cannot really test it, but can you try replacing your

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() {

}
)

这篇关于R尝试捕获块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆