R warning() wrapper - raise to parent function

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).

Tags:

R