0

I am trying to track the number of times certain functions are called from the console. My plan is to add a simple function such as "trackFunction" in each function that can check whether they have been called from the console or as underlying functions.

Even though the problem sounds straight-forward I can't find a good solution to this problem as my knowledge in function programming is limited. I've been looking at the call stack and rlang::trace_back but without a good solution to this.

Any help is appreciated.

Thanks

1 Answers1

0

A simple approach would be to see on which level the current frame lies. That is, if a function is called directly in the interpreter, then sys.nframe() returns 1, otherwise 2 or higher.

Relate:

Rscript detect if R script is being called/sourced from another script

myfunc <- function(...) {
  if (sys.nframe() == 1) {
    message("called from the console")
  } else {
    message("called from elsewhere")
  }
}

myfunc()
# called from the console

g <- function() myfunc()
g()
# called from elsewhere

Unfortunately, this may not always be intuitive:

ign <- lapply(1, myfunc)
# called from elsewhere
for (ign in 1) myfunc()
# called from the console

While for many things the lapply-family and for loops are similar, they behave separately here. If this is a problem, perhaps the only way to mitigate this is the analyze/parse the call stack and perhaps "ignore" certain functions. If this is what you need, then perhaps this is more appropriate:

R How to check that a custom function is called within a specific function from a certain package

r2evans
  • 141,215
  • 6
  • 77
  • 149
  • 1
    Hi r2evans, thanks for the detailed reply. What I meant with "called from the console" is any function called from there i.e if I run func1(func2(func3))) then I consider all 3 were run from the console. However sys.nframe() will return 1,2,3 respectively. Further issue is the pipe operator if I do "arg1" %>% func1 %>% func2 %>% func3 I also consider them called from the console and the sys.nframe() is even less reliable. So I guess it has to come from the analysis of the first environment – Jack212 Aug 13 '20 at 07:42
  • Good luck, then. My only thought is following my second link, and broadening the list of acceptable packages/functions (since many of your calls from the console will have one or more parent/calling functions). – r2evans Aug 13 '20 at 13:42