Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tryCatch() apparently ignoring a warning

I'm writing a function that uses kmeans to determine bin widths to convert a continuous measurement (a predicted probability) into an integer (one of 3 bins). I've stumbled upon an edge case in which it's possible for my algorithm to (correctly) predict the same probability for a whole set, and I want to handle that situation. I'm using the rattle package's binning() function in the following way:

btsKmeansBin <- function(x, k = 3, default = c(0, 0.3, 0.5, 1)) {
  result <- binning(x, bins = k, method = "kmeans", ordered = T)
  bins <- attr(result, "breaks")
  attr(bins, "names") <- NULL
  bins <- bins[order(bins)]
  bins[1] <- 0
  bins[length(bins)] <- 1
  return(bins)
}

Run this function on x <- c(.5,.5,.5,.5,.5,.5), and you'll get an error at the order(bins) step, because bins will be NULL and therefore not a vector.

Obviously, if x has only one distinct value, kmeans shouldn't work. In this case, I'd like to return the default bin divisions. When this happens, binning issues "Warning: the variable is not considered." So I'd like to use tryCatch to handle this warning, but surrounding the result <- ... line with the following code doesn't work the way I expect:

...
tryCatch({
  result <- binning(x, bins = k, method = "kmeans", ordered = T)
}, warning = function(w) {
  warn(sprintf("%s. Using default values", w))
  return(default)
}, error = function(e) {
  stop(e)
})
...

The warning gets printed as though I hadn't used tryCatch, and the code progresses past the return statement and throws the error from order again. I have tried a bunch of variations to no avail. What am I missing, here??

like image 256
Claire Sannier Avatar asked Feb 18 '23 11:02

Claire Sannier


1 Answers

If you look in binning I think you'll find that the "warning" you see is not generated via warning() but with cat(), which is why tryCatch isn't picking it up. The author of binning probably deserves a few lashings with a wet noodle for this oversight. ;) (Or it could be on purpose due to the particular way that rattle works, I'm not sure.)

It appears to return NULL when this happens, so you could simply handle it manually. Not ideal, but possibly the only way to go.

like image 163
joran Avatar answered Feb 22 '23 00:02

joran