[R] combining lists with same names with 'c'

Eric Archer Eric.Archer at noaa.gov
Thu Feb 15 16:33:09 CET 2007


Thanks Duncan!  That's the perfect solution as the update will always 
have all elements named.  I don't think I would've come up with it on my 
own.

Cheers,
e.

Duncan Murdoch wrote:
> On 2/15/2007 5:59 AM, Eric Archer wrote:
>> I recently ran across an unexpected problem caused by combining lists 
>> that contained elements of the same name.  I naively thought that the 
>> elements would get overwritten, but rather the "new" element gets 
>> added with the same name. A simplified version is :
>>
>>  > my.list <- list(a = 1)
>>  > new.list <- c(my.list, list(a = "a", b = "b"))
>>  > new.list
>> $a
>> [1] 1
>>
>> $a
>> [1] "a"
>>
>> $b
>> [1] "b"
>>
>>  > new.list$a
>> [1] 1
>>
>>
>> I think I understand why this happens, but is there a way to do this 
>> kind of combining and force overwriting if the list already contains 
>> an equivalent name?  I can imagine a way using 'lapply', but I'm just 
>> checking to see if there is a way to do it with 'c'.  In the cases 
>> I'd be using this, I wouldn't necessarily know beforehand if the new 
>> list contained unique elements or was an "update" list.
>
> If you know that your update always has all elements named, you could 
> use something like this:
>
> > my.list <- list(a = 1, c = 2)
> > update <- list(a = "a", b = "b")
> > my.list[names(update)] <- update
> > my.list
> $a
> [1] "a"
>
> $c
> [1] 2
>
> $b
> [1] "b"
>
>
> If some elements of the update are named and some are not, I think 
> you'll need several steps:
>
> Check if any are named.  If so, use the method above for the named 
> entries.
>
> If any are not named, decide what to do with them, e.g. use c() to put 
> them on the end of the result, ignore them, whatever.
>
> Duncan Murdoch
>
>


-- 

Eric Archer, Ph.D.
NOAA-SWFSC
8604 La Jolla Shores Dr.
La Jolla, CA 92037
858-546-7121,7003(FAX)
eric.archer at noaa.gov
http://swfsc.noaa.gov/prd-etp.aspx

"Innocence about Science is the worst crime today."
   - Sir Charles Percy Snow


"Lighthouses are more helpful than churches."
   - Benjamin Franklin

   "...but I'll take a GPS over either one."
       - John C. "Craig" George



More information about the R-help mailing list