简体   繁体   English

在不同的环境中调用R函数

[英]Calling an R function in a different environment

I fell like it should be fairly straightforward to do this, but I can't for the life of me find a solution... I want to evaluate an R function in an environment different from the one where it is. 我觉得这样做应该相当简单,但我不能为我的生活找到解决方案......我想在一个不同于它的环境中评估一个R函数。

What I'd like: 我想要的是什么:

# A simple function
f <- function() {
  x + 1
}

# Create an env and assign x <- 3
env <- new.env()
assign("x", 3, envir = env)

# Call f on env
call_on_env(f, env)
#> 4

The closest I got to " call_on_env() " was: 我最接近“ call_on_env() ”的是:

# Quote call and evaluate
quo <- quote(f())
eval(quo, envir = env)

Unfortunately the code above returns an error: Error in f() : object 'x' not found . 不幸的是,上面的代码返回一个错误: Error in f() : object 'x' not found的错误: Error in f() : object 'x' not found So then... Is there a way for me to evaluate f() on env ? 那么......有没有办法让我评估env上的f()

Edit: I'm able to send f() to env and then call it, but this leaves f() permanently there. 编辑:我能够将f()发送到env ,然后调用它,但这会永久地留下f() For context [see below], I want to call the function in parallel with some pre-loaded packages. 对于上下文[见下文],我想与一些预加载的包并行调用该函数。

Context: I'm calling a function in parallel with parallel::clusterMap() and I'd like for the packages loaded in my global environment to also be loaded on the clusters. 上下文:我正在调用一个与parallel::clusterMap()的函数,我希望在我的全局环境中加载的包也可以加载到集群上。 As far as I can tell, parallel::clusterExport() can only export a list of variables, so it doesn't work for me... 据我所知, parallel::clusterExport()只能导出一个变量列表,所以它对我不起作用......

Move f into env f移至env

environment(f) <- env
f()
# [1] 4

Note: Evaluation of objects across different environments is not desirable, as you have encountered here. 注意:正如您在此处遇到的那样,不希望在不同环境中评估对象。 It's best to keep all objects that you plan to interact with one another in the same environment. 最好将所有计划在同一环境中相互交互的对象保留在一起。

If you don't want to change the environment of f , you could put all the above into a new function. 如果您不想更改f的环境,可以将以上所有内容放入新功能中。

fx <- function(f, env) {
    environment(f) <- env
    f()
}
fx(f, env)
# [1] 4

The source() function might help: source()函数可能会有所帮助:

source('scriptfilename.R')

If the file is located in another path then use: 如果文件位于另一个路径中,则使用:

source('YOURPATH/scriptfilename.R')

When you run source() it will pull all of the functions into your current Environment. 运行source()它会将所有函数拉入当前环境。 You can then reference any of the functions contained in the R script where it sits. 然后,您可以引用R脚本中包含的任何函数。

However I wouldn't recommend referencing functions/scripts outside of your R project folder structure, since the links will break if you share your R project folder with others. 但是,我不建议在R项目文件夹结构之外引用函数/脚本,因为如果与其他人共享R项目文件夹,链接将会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM