Crops
Crops

Reputation: 5162

Adding more details after an error message in R

I have a function similar to the one below where a matrix is created within a loop.

foo <- function(x, y, z) {
  out <- list(a1 = NULL, a2 = NULL, a3 = NULL)
  for (i in 1:3) {
    t <- 100 * i
    a <- matrix(x, y + t, z)
    out[[i]] <- t(a)
  }
  return(out)
}

The following runs fine. p <- foo(NA, 100, 50)

But the following gives the cannot allocate vector of length error

q <- foo(NA, 3500000, 50)

I want to add some additional message like adjust arguments 'y' and 'z' after the cannot allocate vector of length or too many elements specified errors whenever they occur in my function.

I am trying try and tryCatch, but can't seem to get the desired result when the error is occurring within a loop. How to do this?

Upvotes: 1

Views: 96

Answers (1)

Colonel Beauvel
Colonel Beauvel

Reputation: 31161

You can enrich the error message with a simple decorator pattern:

safify <- function(f){
    function(...){
        tryCatch({
            f(...)
        },
        error=function(e){
            msg=conditionMessage(e)
            if(grepl("cannot allocate", msg)){
                msg=paste(msg, " Adjust arguments 'y' and 'z'", sep='.')
                return(msg)
            }
            msg
        })
    }
}

safefoo = safify(foo)

#res=safefoo(NA, 3500000, 50)
#> res
#[1] "cannot allocate vector of size 667.6 Mb. Adjust arguments 'y' and 'z'"

This way you catch every type of error which might occur and you enrich the one you want.

Upvotes: 4

Related Questions