Denis
Denis

Reputation: 12087

How do I get a unique named list?

This is a simple question and I think I can probably re-invent the wheel and write something custom but I'm sure there must be an easy way to do this that I can't think of at the moment. Suppose I have a list:

l <- list("NY"=10001, "CT"=10002, "CT"=10002)

I would like a list:

list("NY"=10001, "CT"=10002)

I tried to use unique(l) but it just returns:

list(10001, 10002)

How do I get a unique list but preserve the names assigned to the values?

Upvotes: 4

Views: 80

Answers (3)

s_baldur
s_baldur

Reputation: 33743

Given that

Each string is mapped to 1 number

we can do:

l[unique(names(l))]

Edit:, another alternative

tapply(l, names(l), `[`, 1)

Upvotes: 3

LuukvGorp
LuukvGorp

Reputation: 66

Try the duplicated function:

l=list("NY"=10001, "CT"=10002, "CT"=10002)
l[!duplicated(l)]

Results in:

$NY
[1] 10001

$CT
[1] 10002

Upvotes: 1

zx8754
zx8754

Reputation: 56259

Using duplicated:

l[ !duplicated(l) ]

Upvotes: 4

Related Questions