Reputation:
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?
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)))
}
)
Upvotes: 2
Views: 1009
Reputation: 3297
I cannot really test it, but can you try replacing your
if (TRUE)
condition with this:
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() {
}
)
Upvotes: 1