[R] add vectors to multiple objects

David Winsemius dwinsemius at comcast.net
Fri Aug 3 23:45:23 CEST 2012


On Aug 3, 2012, at 2:11 PM, R. Michael Weylandt wrote:

> On Fri, Aug 3, 2012 at 2:53 PM, John linux-user <johnlinuxuser at yahoo.com 
> > wrote:
>> Maybe what I previously posted was not clear enough or something  
>> else. All vectors L1,L2.. and objects (e.g. a.list, b.list, c.list)  
>> already exit or easily to be created in a workspace. Do not worry  
>> about those. The key question is how to systematically append/ 
>> assign these vectors to many objects (hundreds) in a loop without  
>> explicitly typing these object names one by one. Please refer to my  
>> code posted below to detail my question.  I really appreciate your  
>> ideas/suggestions. John
>>
>
> Like David, I find this still somewhat confusing, but perhaps this
> will get you started:
>
> a3 <- 1:4
> b3 <- 6
> c3 <- letters
>
> a_new_thing <- do.call(list, lapply(ls(pattern = "3"), get))
>
> old_thing <- list("cow")
>
> a_longer_old_thing <- c(old_thing, a_new_thing)
>
> adapt as needed.

Heh. Users of this should realize that Michael probably did this in  
clean session. If you run it with any other items in the workspace  
that have  "3" in their names they get wrapped up too. I had a 300  
line dataframe as well as a function whose values both got gathered up.

In the case where one needed to isolate a disjoint group of items, one  
might want to create an environment in which to segregate those items.  
the ls function can be directed to look in only one environment.

I wondered if this were the route intended:

for( i in seq_along(ls(patt=".lst") ) ) {
            assign( ls(patt=".lst")[i],  # the name of the i-th ".lst"- 
item
                    append(
                       sapply(ls(patt=".lst$"), get)[i],  # the  
original value
                       sapply(ls(patt="^L\\d"), get)[i] ) )} # the  
appended i-th "L"-value

I think it is far from optimal to have a loose collection of objects  
in the workspace. Much better to have them all in one list or an  
environment.

-- 

David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list