Question

Is it possible to source methods to an environment other than .GlobalEnv?

I'm slowly getting a bit frustrated over R's masking mechanism (I'll probably be back with an own question in this respect, but if you're interested, for the moment just try using packages RMySQL and RSQLite in the same process and loading them in this order; makes my RMySQL stuff crash) and would very very much like to switch to consistently using <namespace>::foo() instead of just foo() throughout all of my scripts.

Yet, using <namespace>::foo() is less efficient than using a "local copy" (e.g. namespace..foo <- <namespace>::foo(); I can provide examples for those interested, but it's very easy to test for yourself).

Making local copies works a treat for other packages I'm loading since (most of them) do have a namespace, but before my own code turns "package" it does not.

So I though "let's just source my stuff to NS <- newenv(parent=emptyenv()) and then apply the same routine as for the other packages". But R won't let me:

setGeneric(
    name="fooBar",
    signature=c("src"),
    def=function(src, ...){
        standardGeneric("fooBar")    
    }
)
setMethod(
    f="fooBar",
    signature=signature(src="character"),
    definition=function(src, ...){
        cat(src, sep="\n")        
    }
)
# These would go into: 
"Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/gnrc.R"
"Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/mthd.R"

# This works:
source("Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/gnrc.R")
source("Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/mthd.R")

# This does not:
NS <- new.env(parent=emptyenv())
source("Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/gnrc.R", local=NS)
source("Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/mthd.R", local=NS)

eval(parse(file="Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/gnrc.R"), envir=NS)
eval(parse(file="Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/mthd.R"), envir=NS)

Errors:

> source("Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/gnrc.R", local=NS)
Error in eval.with.vis(expr, envir, enclos) : 
  could not find function "setGeneric"
> source("Q:/usr/wsp/3.6.2/32bit/root/_SCRATCH/mthd.R", local=NS)
Error in eval.with.vis(expr, envir, enclos) : 
  could not find function "setMethod"

Any idea what I might be doing wrong?

Was it helpful?

Solution

OMG! I'm sorry guys, this is somewhat embarrassing:

I've switched to using new.env(parent=emptyenv()) consistently in order to prevent some memory ballooning when caching environments and got so used to it that I forgot that it does make sense to have different parent envirs at time ;-)

In this case NS <- new.env() will do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top