如何检查是否已从控制台调用函数?

问题描述

我正在尝试跟踪从控制台调用某些功能次数。 我的计划是在每个函数添加一个简单的函数,例如“ trackFunction”,以检查它们是否已从控制台调用或作为基础函数调用

尽管问题听起来很简单,但由于我对函数编程的了解有限,所以我找不到很好的解决方案。我一直在看调用栈和rlang :: trace_back,但是对此没有很好的解决方案。

感谢您的帮助。

谢谢

解决方法

一种简单的方法是查看当前帧位于哪个级别。也就是说,如果直接在解释器中调用函数,则sys.nframe()返回1,否则返回2或更高版本。

相关:

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

不幸的是,这可能并不总是很直观:

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

尽管lapply-系列和for循环在很多方面都相似,但它们在这里分别表现。如果这是一个问题,减轻这种情况的唯一方法可能就是分析/解析调用堆栈,并可能“忽略”某些功能。如果这是您需要的要求,那么也许这更合适:

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