Duplicate list names in R

后端 未结 1 1931
死守一世寂寞
死守一世寂寞 2020-12-11 01:34

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\         


        
相关标签:
1条回答
  • 2020-12-11 02:20

    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.

    0 讨论(0)
提交回复
热议问题