Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R warning() wrapper - raise to parent function

Tags:

r

I have a wrapper around the in-built warning() function in R that basically calls warning(sprintf(...)):

warningf <- function(...)
    warning(sprintf(...))

This is because I use warning(sprintf(...)) so often that I decided to make a function out of it (it's in a package I have of functions I use often).

I then use warningf when I write functions. i.e., instead of writing:

f <- function() {
    # ... do stuff
    warning(sprintf('I have %i bananas!',2))
    # ... do stuff
}

I write:

f <- function() {
    # ... do stuff
    warningf('I have %i bananas!',2)
    # ... do stuff
}

If I call the first f(), I get:

Warning message:
In f() : I have 2 bananas!

This is good - it tells me where the warning came from f() and what went wrong.

If I call the second f(), I get:

Warning message:
In warningf("I have %i bananas!",2) : I have 2 bananas!

This is not ideal - it tells me the warning was in the warningf function (of course, because it's the warningf function that calls warning, not f), masking the fact that it actually came from the f() function.

So my question is : Can I somehow "raise" the warning call so it displays the warning in f() message instead of the warning in warningf ?

like image 753
mathematical.coffee Avatar asked Mar 07 '12 06:03

mathematical.coffee


1 Answers

One way of dealing with this is to get a list of the environments in your calling stack, and then pasting the name of the parent frame in your warning.

You do this with the function sys.call() which returns an item in the call stack. You want to extract the second from last element in this list, i.e. the parent to warningf:

warningf <- function(...){
  parent.call <- sys.call(sys.nframe() - 1L)
  warning(paste("In", deparse(parent.call), ":", sprintf(...)), call.=FALSE)
}  

Now, if I run your function:

> f()
Warning message:
In f() : I have 2 bananas! 

Later edit : deparse(parent.call) converts the call to a string in the case that the f() function had arguments, and shows the call as it was specified (ie including arguments etc).

like image 139
Andrie Avatar answered Sep 21 '22 14:09

Andrie