R 检查包中的函数是否是从包 fun 或外部调用的

标签 r devtools

如何从包(导出)函数中检查当前函数执行是否已被该包中的函数调用,或者是否被外部包/全局环境调用。

我目前的方法是通过实验开发的:

myfun <- function(){
    current_call = sys.call()
    parent_call = sys.call(sys.parent())
    if(identical(current_call,parent_call) || !identical(environmentName(parent.env(environment(match.fun(parent_call[[1L]])))),"imports:mypkg")){
        cat("called externally\n")
    }
}

似乎不处理依赖于我的包的其他包中构造的匿名函数。
不是特别与 devtools 相关,而是与 devtools 很好地解决的包开发相关。

编辑:
目标是在任何情况下调用操作(上例中的 cat()),除了来自同一包中的其他函数的调用。

最佳答案

借用data.table:::cedta,我将这两个函数放在一个名为test的包中

myfun <- function() {
  te <- topenv(parent.frame(1))
  if(isNamespace(te) && getNamespaceName(te) == "test") { # <-- "test" is the name of the package
    cat("called from my package\n")
  } else cat("Not called from my package\n")
}

tester <- function() {
  myfun()
}

加载test包后,我得到了这些结果

test:::myfun()
#Not called from my package
test:::tester()
#called from my package

关于R 检查包中的函数是否是从包 fun 或外部调用的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27870542/

相关文章:

r - 无法在 centOS 7.0 64 位上安装 git2r 或 devtools R 包

r - 为什么 devtools 给我一个警告,@slot 需要名称和描述

r - 如何自动将函数加载到 R 包的命名空间中

c++ - MacOS Big Sur M1 芯片,R devtool monocle3 安装期间出现 cmath 错误

R如何有条件地更新数据框中的数值

r - 查找当前.R文件的位置

r - 出现错误 : Reading objects from shinyoutput object not allowed - multiple linear regression model

r - 在 R 的正则表达式中使用组和反向引用 - stringr::str_replace

r - 如何使用shiny将数据框数据显示到R表中

css - 元素在开发工具中消失