Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206278

How to get the name of the calling function inside the called routine?

$
0
0

Is there a "non-Internal" way to get the caller's name, as the function stop does?

The idea is that I have a small function that checks the inputs and halts execution if some condition is not met. This function is called by several others, that use the same validation code. If the input is invalid, the caller's environment is dumped (so I can see arguments passed to the function), and execution halts.

Simplified example:

check <- function(x)
{
    if(x<0)
    {
        print(as.list(parent.frame()))

        evalq(stop("invalid input."), parent.frame())
    }
}

test <- function(x, y)
{
    check(x)
}

I thought that evaluating the expression quote(stop("blah")) in the caller's environment would make it show the caller's name. However, the result is the following:

test(-1, 2)

# $x
# [1] -1
# 
# $y
# [1] 2
# 
# Error in eval(substitute(expr), envir, enclos) : invalid input.

And this doesn't change if I use parent.frame(n) with n>1 in evalq.

So here is the question, actually two questions: 1. Is there a way to get the name of the function that created an environment (assuming it was created as such)? 2. Why the workaround above fails?

EDIT: I said the workaround above fails because I wanted the error message to appear as

Error in test(x, y) : invalid input.

as if the stop statement were a part of test body. So question 2 can be restated as: 2': Why didn't the evaluation of stop("invalid input.") capture the caller's name, considering it was evaluated in the environment of the caller?


Viewing all articles
Browse latest Browse all 206278

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>