Reputation: 12087
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
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
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