[R] A question about environments

David Vavra davavra at vverizon.net
Tue Jun 3 22:09:49 CEST 2008


I have been using separate environments to partition my data and functions
into logical groups but I have been having an odd (to me) problem.

To load and manipulate the data environments, I wrote a couple of small
functions (see below). The problem seems to be that when I initially try to
load the environment, often no data can be found but if I repeat the
function call, it then works.

It appears that the CreateEnv function sometimes returns a different
environment value than as.environment does. Not always, this is puzzling. I
discovered this by saving the returned value. That environment contains the
data. 

Can someone tell me where I am going wrong? 

Thanks,
DAV

 -------

# return a named environment or, if needed, create and attach it

CreateEnv <- 
function(name, clear=FALSE) {
	if (name %in% search()) {
		env <- as.environment(name)
		if (clear)
			rm(list=ls(name),envir=env)
		return(env)
	}
	env <- new.env()
	attach(env, name=name)
	env
}

LoadEnv <-
function (envname, fname=NULL, ret=FALSE) {
	if (is.null(fname)) fname <- paste(envname,'Rdata',sep='.')
	env <- CreateEnv(envname)
	load(file=fname, envir=env)
	if (ret) 
		return(env)
}



More information about the R-help mailing list