rconvenience-methods

Convenience function for exporting objects to the global environment


UPDATE: I have added a variant of Roland's implementation to the kimisc package.

Is there a convenience function for exporting objects to the global environment, which can be called from a function to make objects available globally?

I'm looking for something like

export(obj.a, obj.b)

which would behave like

assign("obj.a", obj.a, .GlobalEnv)
assign("obj.b", obj.b, .GlobalEnv)

Rationale

I am aware of <<- and assign. I need this to refactor oldish code which is simply a concatenation of scripts:

input("script1.R")
input("script2.R")
input("script3.R")

script2.R uses results from script1.R, and script3.R potentially uses results from both 1 and 2. This creates a heavily polluted namespace, and I wanted to change each script

pollute <- the(namespace)
useful <- result

to

(function() {
pollute <- the(namespace)
useful <- result
export(useful)
})()

as a first cheap countermeasure.


Solution

  • Simply write a wrapper:

    myexport <- function(...) {
      arg.list <- list(...)
      names <- all.names(match.call())[-1]
      for (i in seq_along(names)) assign(names[i],arg.list[[i]],.GlobalEnv)
    }
    
    fun <- function(a) {
      ttt <- a+1
      ttt2 <- a+2
      myexport(ttt,ttt2)
      return(a)
    }
    
    print(ttt)
    #object not found error
    fun(2)
    #[1] 2
    print(ttt)
    #[1] 3
    print(ttt2)
    #[1] 4
    

    Not tested thoroughly and not sure how "safe" that is.