0

I am perofrimn grid search using rpart tree models. On some iteration I got fatal error due to values pass in control argument. Is there an easy way to stop R from crashing if it cannot fit tree in this iteration?

#large_grid


complexity_par_val <- seq(0.001, 0.01, 0.001)
min_bin_val <- seq(500, 5000, 500)
max_depth_val <- seq(1, 30, 1)

freq_tree_large_grid <- expand.grid(cp = complexity_par_val, min_bin = min_bin_val, max_depth = max_depth_val)

#random serach

set.seed(123)

n_search <- 500

sample_for_r_search <- freq_tree_large_grid[sample(nrow(freq_tree_large_grid), n_search), ]

result_of_r_search_freq_old <- result_of_r_search_freq

result_of_r_search_freq <- data.frame()

start_time <- Sys.time()
for(i in 1:n_search) { 
cp_1 <- sample_for_r_search$cp[i] 
min_bin_1 <- sample_for_r_search$min_bin[i] 
max_depth_1 <- sample_for_r_search$max_depth[i] 

cntr <- list(cp=cp_1, minbucket = min_bin_1, maxdepth = max_depth_1, xval = 0)
sum_dev <- 0
for (j in 1:8){
FREQ_V <- FREQ_TRAIN[FREQ_TRAIN$ValRandom10 == j,]
FREQ_D <- FREQ_TRAIN[FREQ_TRAIN$ValRandom10 != j,]
tryCatch({
tree <- rpart(      formula = formula_tree,
                     data = FREQ_D,
                     method  = "poisson" ,
                     control = cntr
                     )}, error=function(e){})

pred <- predict(tree, newdata = FREQ_V )*FREQ_V$Exposure
Dev <- Deviance_Poisson(pred, FREQ_V$ClaimNb)
sum_dev <- sum_dev+Dev
print('cv')
print(j)
}
CV8_DEV <- sum_dev/8
result_of_r_search_freq <- rbind(result_of_r_search_freq, data.frame(CV8_DEV, cp_1, min_bin_1, max_depth_1))
print('ending the cross validation nr:')
print(i)
}
end_time <- Sys.time()
Miczab
  • 112
  • 10
  • Without the data it is difficult to provide a comprehensive answer. Although this [answer](https://stackoverflow.com/questions/27128455/r-try-catch-block) is old, it may still help you. If it doesn't, add a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Kat Aug 25 '21 at 14:55
  • When an error occurs in an R for-loop from the console, the value of the loop index stays in the global environment, so you can start your debugging by looking at the variables that are created by passing that value to any expression that has the loop index in it. (You _should_ be presenting the full error message when asking debugging questions on SO.) – IRTFM Aug 25 '21 at 19:22

0 Answers0