Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show the name of the parent function in the warning message

Tags:

r

warnings

I have a helper function for displaying warnings:

mywarn <- function() {
  warning("I warn you")
}

If I call the function directly, I get the name of the function where the error occurred:

mywarn()
> Warning message:
  In mywarn() : I warn you

However I want to use the warning function from within several other functions:

myfun <- function(x) {
  x <- x^2
  mywarn()
  x
}

But then it still shows the name of my warning function when warning is displayed:

myfun(10)
> Warning message:
  In mywarn() : I warn you

What is the best way to make the warning message display myfun instead of mywarn ?

like image 716
Karolis Koncevičius Avatar asked Oct 11 '25 10:10

Karolis Koncevičius


1 Answers

The simplest way is by explicitly constructing a warning condition object with a suitable call object, and passing that to warning. This overrides the default logic which uses the calling function.

mywarn <- function (call = sys.call(sys.parent())) {
  warning(simpleWarning("I warn you", call))
}
myfun(10)
Warning message:
In myfun(10) : I warn you
like image 89
Konrad Rudolph Avatar answered Oct 16 '25 06:10

Konrad Rudolph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!