2014-11-25 125 views
1

我想在一個循環中評估一些輸出參數的樹。但有時樹函數會中止。線條如何被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))) 
    } 
) 
+0

In錯誤處理程序使用接口'conditionMessage(condition)'和'conditionCall(call)'而不是依賴這些S3類的結構。 – 2014-11-25 15:26:57

+0

我相信你的意思是conditionCall(條件),但我同意。 – user3969377 2014-11-25 16:02:40

回答

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

} 
) 
+0

我在循環之前有一個接收器來捕獲文件中的輸出。如何在條件下捕獲錯誤消息。我用message(condition)替換了write(「Error」,stderr()),但消息沒有寫入文件。 – user3969377 2014-11-25 14:17:52

+0

啊,對不起,我在編輯我的答案後看到了您的評論。您是否可以移除水槽部件,並且只有在出現錯誤時纔將消息添加到文件中?或者這打破了你的輸出? – Nikos 2014-11-25 14:24:22

+0

我必須查看條件的結構,才能打印它。我用「答案」更新了問題,現在已經足夠了...... – user3969377 2014-11-25 14:34:02