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