[R] A question about environments

From: David Vavra <davavra_at_vverizon.net>
Date: Tue, 03 Jun 2008 16:09:49 -0400

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)

}


R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 03 Jun 2008 - 21:52:33 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 03 Jun 2008 - 22:30:40 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive