Kid
Kid

Reputation: 325

How to get the element of a list with the same name?

I would like to create a list of objects with possibly duplicated names. For example:

l <- list("a"=1:4, "a"=2:3, "b"=1)

Now I want to get elements of l whose name is "a" (l[1] and l[2] in this case). Is there any concise way to do that instead of looping over names(l)? Thanks.

Upvotes: 2

Views: 657

Answers (1)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

You can use basic subsetting for this:

> l[names(l) == "a"]
$a
[1] 1 2 3 4

$a
[1] 2 3

(By the way, l is a funky character to use by itself with scripts because of how easily it can be misinterpreted for 1).

Upvotes: 7

Related Questions