[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

Can someone tell me where I am going wrong? 



# 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)
	env <- new.env()
	attach(env, name=name)

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) 

More information about the R-help mailing list