[R] assigning to list element within target environment

Richard D. Morey r.d.morey at rug.nl
Thu Mar 17 13:25:47 CET 2011


I would like to assign an value to an element of a list contained in an 
environment. The list will contain vectors and matrices. Here's a simple 
example:

# create toy environment
testEnv = new.env(parent = emptyenv())

# create list that will be in the environment, then assign() it
x = list(a=1,b=2)
assign("xList",x,testEnv)

# create new element, to be inserted into xList
c = 5:7

Now, what I'd like to do is something like this:

assign("xList[[3]]",c,testEnv)

But the assign() help says:
"assign does not dispatch assignment methods, so it cannot be used to 
set elements of vectors, names, attributes, etc."

So that's no good. Also, this fails:
attach(testEnv)
xList[[3]] <<- c
detach(testEnv)

because, as the attach() help says:
"If you use <<- or assign to assign to an attached database, you only 
alter the attached copy, not the original object."

What I've been doing is making a copy of xList in the local environment, 
changing it, then using assign() to make the change in the testEnv 
environment. This is unsatisfactory due to the double use of memory 
making a copy of testEnv (the actual list I will use will be quite large).

Another option would be this:

# Assign the new element to a variable in the target environment
assign("temp",c,testEnv)
# "Assign" it within the target environment, from the temp variable
eval(parse(text="xList[[3]]=temp"),env=testEnv)
# remove the unneeded variable
rm("temp",envir=testEnv)

But I figure there must be a more elegant way. Anyone have any ideas?

Thanks,
Richard

--
Richard D. Morey
Assistant Professor
Psychometrics and Statistics
Rijksuniversiteit Groningen / University of Groningen
http://drsmorey.org/research/rdmorey



More information about the R-help mailing list