R尝试catch块
我想在一个循环中评估一些输出参数的树。但有时树函数会中止。线条如何被try catch块包围?R尝试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)))
}
)
我真的不能测试,但你能尝试更换您的
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() {
}
)
我在循环之前有一个接收器来捕获文件中的输出。如何在条件下捕获错误消息。我用message(condition)替换了write(“Error”,stderr()),但消息没有写入文件。 – user3969377 2014-11-25 14:17:52
啊,对不起,我在编辑我的答案后看到了您的评论。您是否可以移除水槽部件,并且只有在出现错误时才将消息添加到文件中?或者这打破了你的输出? – Nikos 2014-11-25 14:24:22
我必须查看条件的结构,才能打印它。我用“答案”更新了问题,现在已经足够了...... – user3969377 2014-11-25 14:34:02
In错误处理程序使用接口'conditionMessage(condition)'和'conditionCall(call)'而不是依赖这些S3类的结构。 – 2014-11-25 15:26:57
我相信你的意思是conditionCall(条件),但我同意。 – user3969377 2014-11-25 16:02:40