R:在命名环境中存储类似的功能

时间:2016-12-26 00:55:21

标签: r namespaces

我觉得在环境中对类似功能进行分组很方便。

myenv <-  new.env()
f <- function() print(1)
assign("f", f, myenv)
rm(f) # use before attach to avoid  "object is masked" message
attach(myenv)
rm(myenv)

通过这种方式,我可以列出相关的功能:

ls("myenv")
# [1] "f"   # and any other possible function defined in myenv

无论如何,当我打印功能时:

f
# function() print(1)
# <environment: 0x000000001df15d80>

我只获得了对环境哈希的引用,而获得对包的实际名称的引用会很好:

sd
function (x, na.rm = FALSE) 
sqrt(var(if (is.vector(x) || is.factor(x)) x else as.double(x), 
    na.rm = na.rm))
<bytecode: 0x000000001c01d8a8>
<environment: namespace:stats>

是否有可能或我被迫创建一个包?

1 个答案:

答案 0 :(得分:1)

有一些代码,因此将它存储在单独的函数中很方便。

print.store.f <- function(x, useSource = TRUE, ...) {
    class(x) <- NULL
    print.function(x, useSource = TRUE, ...)
    cat("<environment: myEnv>\n")
}
storeInEnv <- function(fun, env){
    if( ! env  %in% search()) attach(new.env(), name=env)        
    assign(fun, get(fun, parent.frame()), as.environment(env))
    eval(parse(t=sprintf("class(%s) <- 'store.f'", fun)), as.environment(env))
    rm(list=fun, pos=parent.frame())
}

现在,在创建一个函数之后:

f <- function() print(1)

可以将其存储在必要时创建的环境中

storeInEnv("f", "myenv")  

现在:

f
# function() print(1)
# <environment: myEnv>

请注意,该功能已从全局环境中删除,仅存在于myenv

getAnywhere(f)
# A single object matching 'f' was found
# It was found in the following places
#   myenv
# with value
#  
# function() print(1)
# <environment: myEnv>