[英]R user-defined functions in new environment
I use some user-defined small functions as helpers. 我使用一些用户定义的小函数作为助手。 These functions are all stored in a
R_HOME_USER/helper
directory. 这些函数都存储在
R_HOME_USER/helper
目录中。 Until now, these functions were sourced at R start up. 到目前为止,这些功能都是在R启动时获取的。 The overall method is something like `lapply(my.helper.list,source).
总体方法类似于`lapply(my.helper.list,source)。 I want now these functions to be sourced but not to appear in my environment , as they pollute it.
我现在希望这些函数源化但不出现在我的环境中 ,因为它们会污染它们。
A first and clean approach would be to build a package with all my helper.R. 第一个干净的方法是使用我所有的助手来构建一个程序包。 For now, I do not want to follow this method.
目前,我不想遵循此方法。 A second approach would be to name these helpers with a leading dot.
第二种方法是用一个前导点命名这些助手。 This annoys me to have to run
R > .helper1()
. 这让我不得不运行
R > .helper1()
。
Best way would be to define these helpers in a specific and accessible environment, but I am messing with the code. 最好的方法是在特定且可访问的环境中定义这些帮助程序,但是我搞砸了代码。 My idea is to create first a new environment:
我的想法是首先创建一个新环境:
.helperEnv <- new.env(parent = baseenv())
attach(.helperEnv, name = '.helperEnv')
Fine, R > search()
returns 'helperEnv' in the list. 好的,
R > search()
在列表中返回'helperEnv' 。 Then I run : 然后我运行:
assign('helper1', helper1, envir = .helperEnv)
rm(helper1)
Fine, ls(.helperEnv)
returns 'helper1' and this function does not appear anymore in my environment. 很好,
ls(.helperEnv)
返回'helper1',并且此功能在我的环境中不再出现。 The issue is I can't run helper1 (object not found). 问题是我无法运行helper1(找不到对象)。 I guess I am not on the right track and would appreciate some hints.
我想我走的路不正确,请多多指教。
I think you should assign the pos
argument in your call to attach
as a negative number: 我认为您应该在调用中分配
pos
参数以attach
为负数:
.helperEnv <- new.env()
.helperEnv$myfunc<-function(x) x^3+1
attach(.helperEnv,name="helper",pos=-1)
ls()
#character(0)
myfunc
#function(x) x^3+1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.