Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple example of using tryCatch()

I am struggling to figure out how to use tryCatch() to throw an error. I have read several blog posts, Hadley's write-up in advanced R and several SO posts. But for some reason, it just hasn't sunk in yet. My dummy example is this: when a vector has a length that is less that 160, stop executing the function and instead provide the user with an error message. Pretty simple stuff but apparently not for me. I feel like this function should do exactly that:

dummy_fun <-  function(x) {
    tryCatch(length(x) < 160 ,
             error = function(e) {
               print("An error message")
             }
    )
  return(x*2)
}

But when I run the function, the error is not caught:

>dummy_fun(airquality$Ozone)

  [1]  82  72  24  36  NA  56  46  38  16  NA  14  32  22  28  36  28  68  12  60  22   2  22   8  64  NA  NA  NA  46  90 230  74
 [32]  NA  NA  NA  NA  NA  NA  58  NA 142  78  NA  NA  46  NA  NA  42  74  40  24  26  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 270
 [63]  98  64  NA 128  80 154 194 194 170  NA  20  54  NA  14  96  70 122 158 126  32  NA  NA 160 216  40 104 164 100 128 118  78
 [94]  18  32 156  70 132 244 178 220  NA  NA  88  56 130  NA  44 118  46  62  88  42  18  NA  90 336 146  NA 152 236 168 170 192
[125] 156 146 182  94  64  40  46  42  48  88  42  56  18  26  92  36  26  48  32  26  46  72  14  28  60  NA  28  36  40

Even though length is clearly less than 160.

>length(airquality$Ozone) < 160
[1] TRUE

If I use stop or stopifnot, it stops the code but then automatically opens up the debugging window (at least in RStudio) whereas I'd just like an error, telling the user that there is an error:

dummy_fun2 <-  function(x) {
  stop(length(x) < 160 ,"An error message")
  return(x*2)
}

dummy_fun2(airquality$Ozone)

And stopifnot:

dummy_fun3 <-  function(x) {
  stopifnot(length(x) < 160 ,"An error message")
  return(x*2)
}

dummy_fun3(airquality$Ozone)

So, I am curious if anyone has any idea what I am doing wrong here. I'm sure I'll get this labelled as a duplicate post but I truly am lost with this.

like image 277
boshek Avatar asked Aug 05 '26 20:08

boshek


1 Answers

dummy_fun <-  function(x) {
  if (length(x) < 160) stop("x is not big enough")
  return(x*2)
}
dummy_fun(airquality$Ozone)
dummy_fun(rep(1, 50))
dummy_fun(rep(1, 500))
like image 120
CJ Yetman Avatar answered Aug 08 '26 11:08

CJ Yetman