r - How to attach a function to my package's namespace after it's loaded? -


this may seem weird question, have use case i'm trying figure out.

suppose i'm writing package , have function want allow user alias else - user provides name of function. i'm wondering what's best way achieve this?

#' @export foo <- function() "hello" #' @export addalias <- function(x) assign(x, foo, envir = globalenv()) 

this behaviour want - user can call addalias("bar") , if calls bar() it'll if called function.

obviously not nice solution because assigns global environment. have feedback on best way this? few methods tried:

1. assigning globalenv

just showed in example. seemed work.

2. assigning package's environment

addalias <- function(x) assign(x, foo, as.environment("package:mypackage")) 

this worked great while until realized works devtools , not if package loaded because of locked environments

3. attaching new env searchpath

.onload <- function(libname, pkgname) {   assign("aliases", new.env(), envir = parent.env(environment()))   attach(aliases)   invisible() }  addalias <- function(x) assign(x, foo, aliases) 

this don't because of use of attach. warranted in case? when detach?

4. expose separate named environment

#' @export #' @keywords internal aliases <- new.env()  addalias <- function(x) assign(x, foo, aliases) 

this works, instead of being able call bar(), user needs call alises$bar() or mypackage::aliases$bar(). don't that, interesting experiment. don't know if it's ok export variable that?

any appreciated

i think more appropriate way use closure.

#' @export foo <- function() "hello" #' @export getfoo <- function() {     function(){         # anything, including running foo()         foo()     } } 

with this, can do

> bar <- getfoo() > bar() [1] "hello" 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -