Duplicate list names in R

2019-01-19 14:10发布

问题:

What's going on here when there are duplicate list names in R?

l <- list()
l[["A"]] <- 5
l[["B"]] <- 7
l[["C"]] <- 9
names(l) <- c("B", "B", "C")

Typing l[["B"]] returns

$B
[1] 5

Typing l returns

$B
[1] 5

$B
[1] 7

$C
[1] 9

Is there a standard way to retrieve all values for the "key" "B"?

回答1:

When you have duplicate names and you call a subset by name, only the first element is returned. In fact, [[ will only ever give you one element anyway, so let's look at [ instead.

l["B"]
# $B
# [1] 5

We can also see that trying c("B", "B") as the subset won't even give us the right result because R goes back and gets the first B again.

l[c("B", "B")]
# $B
# [1] 5
#
# $B
# [1] 5

One of the safest ways to retrieve all the B elements is to use a logical subset of the names() vector. This will give us the correct elements.

l[names(l) == "B"]
# $B
# [1] 5
#
# $B
# [1] 7

This is a great example of why duplicate names should be avoided.