问题描述
.Rprofile中有一些便捷功能,例如方便的函数,用于返回内存中对象的大小.有时我想清理工作空间而不重新启动,而我用rm(list=ls())
删除了所有用户创建的对象和自定义函数.我真的很想不要炸毁我的自定义功能.
I have a few convenience functions in my .Rprofile, such as this handy function for returning the size of objects in memory. Sometimes I like to clean out my workspace without restarting and I do this with rm(list=ls())
which deletes all my user created objects AND my custom functions. I'd really like to not blow up my custom functions.
解决此问题的一种方法似乎是使用我的自定义函数创建一个包,以使我的函数最终位于自己的名称空间中.并不是特别困难,但是有没有更简单的方法来确保自定义函数不会被rm()杀死?
One way around this seems to be creating a package with my custom functions so that my functions end up in their own namespace. That's not particularly hard, but is there an easier way to ensure custom functions don't get killed by rm()?
推荐答案
将attach
和sys.source
合并为一个环境并附加该环境.在这里,文件my_fun.R
中有两个功能:
Combine attach
and sys.source
to source into an environment and attach that environment. Here I have two functions in file my_fun.R
:
foo <- function(x) {
mean(x)
}
bar <- function(x) {
sd(x)
}
在加载这些功能之前,显然找不到它们:
Before I load these functions, they are obviously not found:
> foo(1:10)
Error: could not find function "foo"
> bar(1:10)
Error: could not find function "bar"
创建一个环境并将文件来源添加到其中:
Create an environment and source the file into it:
> myEnv <- new.env()
> sys.source("my_fun.R", envir = myEnv)
由于我们没有附加任何东西,因此仍然不可见
Still not visible as we haven't attached anything
> foo(1:10)
Error: could not find function "foo"
> bar(1:10)
Error: could not find function "bar"
,当我们这样做时,它们是可见的,并且由于我们将环境的副本附加到了搜索路径,因此功能可以通过rm()
-ed来保存:
and when we do so, they are visible, and because we have attached a copy of the environment to the search path the functions survive being rm()
-ed:
> attach(myEnv)
> foo(1:10)
[1] 5.5
> bar(1:10)
[1] 3.027650
> rm(list = ls())
> foo(1:10)
[1] 5.5
我仍然认为您最好使用自己的个人包裹,但同时满足以上要求即可.只要记住搜索路径上的副本就是 copy 即可.如果这些功能相当稳定并且您没有对其进行编辑,那么上面的内容可能会有用,但是比开发这些功能并对其进行修改时要麻烦的多.
I still think you would be better off with your own personal package, but the above might suffice in the meantime. Just remember the copy on the search path is just that, a copy. If the functions are fairly stable and you're not editing them then the above might be useful but it is probably more hassle than it is worth if you are developing the functions and modifying them.
第二种选择是将它们全部命名为.foo
而不是foo
,因为除非设置了参数all = TRUE
,否则ls()
不会返回这样命名的对象:
A second option is to just name them all .foo
rather than foo
as ls()
will not return objects named like that unless argument all = TRUE
is set:
> .foo <- function(x) mean(x)
> ls()
character(0)
> ls(all = TRUE)
[1] ".foo" ".Random.seed"
这篇关于在R中隐藏个人功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!