如何在 R 中引用函数中的本地环境? [英] How can I reference the local environment within a function, in R?

查看:11
本文介绍了如何在 R 中引用函数中的本地环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

[此问题已在 Spacedman 的 聊天室中得到解决,但我正在发帖为他人的利益着想.]

[This question has been resolved in the chat room, by Spacedman, but I'm posting it for others' benefit in the future.]

我有一个函数,myFunc,它在其中创建 localFunc.(注意:这不是在包中,而是在全局环境中.)我想知道 localFunc 在搜索路径中的位置,因为我想通过 对其进行分析mvbutils::foodweb.

I have a function, myFunc, which creates localFunc inside of it. (NB: this is not in a package, but in the global environment.) I'd like to know where localFunc exists in the search path, as I'd like to analyze it via mvbutils::foodweb.

这是一个例子:

myFunc <- function(){
    require(data.table)
    require(mvbutils)
    localFunc <- function(x){
        return(as.data.table(x))
    }
    
    vecPrune <- c("localFunc",ls("package:data.table"))
    ix <- match("data.table",search())
    tmpWeb <- foodweb(where = c(1,ix), prune = vecPrune, plotting = FALSE)
    return(tmpWeb)
}

但是,对 myFunc() 的调用似乎并不表示 localFunc 调用了 data.table().这是不正确的 - 什么给出了?

However, a call to myFunc() does not seem to indicate that localFunc calls data.table(). This is incorrect - what gives?

(注意:where 参数指定搜索路径.)

(NB: The where argument specifies the search path.)

更新 1:正如 Tommy 和 Spacedman 所指出的,诀窍是指定 environment().对 foodweb() 的调用是指 where = c(1, ix).索引 1 是一个错误.这源于认为 .GlobalEnv,通常(总是?)search() 向量中的第一项,是搜索的正确位置.那是错误的.相反,应该参考 environment(),正确的调用如下.(注意:ix 指定 data.table()search() 输出中的位置.)

Update 1: As Tommy and Spacedman point out, the trick is to specify environment(). The call to foodweb() refers to where = c(1, ix). The index 1 is a mistake. That arose from thinking that .GlobalEnv, which is often (always?) the first item in the search() vector, is the right place to search. That is erroneous. Instead, one should refer to environment(), and the correct call is below. (NB: ix specifies the location of data.table() in the search() output.)

tmpWeb <- foodweb(where = c(environment(),ix), prune = vecPrune, plotting = FALSE)

这出现在 this question 的答案中,位于一个名为 checkScriptDependencies 的函数中,该函数将 R 脚本文件中的代码包装到本地函数中,然后由 foodweb 分析.这是一个关于如何使用 environment() 的有限示例,Tommy 已经很好地解释了如何使用它以及在此上下文中的类似函数.

This appears in the answer to this question, in a function called checkScriptDependencies, which wraps the code from an R script file into a local function, which is then analyzed by foodweb. This is a limited example of how to use environment(), and Tommy has given a good explanation of how to use it and similar functions in this context.

推荐答案

要获取当前环境,只需调用environment().

To get the current environment, just call environment().

一般来说,sys.frame 返回当前在调用堆栈上的任何环境,sys.nframe 返回当前调用堆栈的深度.sys.frames 返回调用堆栈上所有环境的列表.

In general, sys.frame returns any of the environments currently on the call stack, and sys.nframe returns the current depth of the call stack. sys.frames returns a list of all environments on the call stack.

environment(f) 返回函数 f 的闭包环境(它将在其中查找函数和全局变量).

environment(f) returns the closure environment for a function f (where it will look for functions and global variables).

parent.env(e) 返回父环境,如果在 e 中找不到符号,它将在该环境中查找.

parent.env(e) returns the parent environment where it will look if a symbol is not found in e.

f <- function() {
  function() list(curEnv=environment(), parent=parent.env(environment()), 
          grandParent=parent.env(parent.env(environment())), callStack=sys.frames(), 
          callStackDepth=sys.nframe())
}
g <- function(f, n=2) if (n>2) g(f, n-1) else f()

floc <- f() # generate a local function
g(floc, 3) # call it

这将调用堆栈深度为 3 的本地函数 floc.它返回一个包含当前环境的列表,它是父级(f 中的本地环境),它是祖父(其中定义了 f,因此是 globalenv).它还返回堆栈帧(环境)列表.这些是 g 中递归调用的环境(除了最后一个是 floc 的当前环境).

This will call the local function floc with a stack depth of 3. It returns a list with the current environment, it's parent (the local environment in f), and it's grand parent (where f was defined, so globalenv). It also returns the list of stack frames (environments). These are the environments for the recursive calls in g (except the last one which is the current environment of floc).

这篇关于如何在 R 中引用函数中的本地环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆