Richard D. Morey
2011-Mar-17 12:25 UTC
[R] assigning to list element within target environment
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
Hadley Wickham
2011-Mar-17 12:33 UTC
[R] assigning to list element within target environment
On Thu, Mar 17, 2011 at 7:25 AM, Richard D. Morey <r.d.morey at rug.nl> wrote:> 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)testEnv$x[[3]] <- c ? Hadley -- Assistant Professor / Dobelman Family Junior Chair Department of Statistics / Rice University http://had.co.nz/