user1389960
user1389960

Reputation: 433

Finding the unique elements in a list without losing element names

l <- as.list(c(1, 1, 2))
names(l) <- c("a", "b", "c")
unique(l)

I would like to find the unique elements in a list without losing the names of the elements in the list. Any suggestions on how to do this?

Upvotes: 2

Views: 1225

Answers (1)

Djork
Djork

Reputation: 3369

There is a bit of conceptual problem, here the unique elements of l are 1 and 2. However, 1 belongs to both "a" and "b", so which name would you want returned for 1? If only the first instance of 1 and the associated name, I would use !duplicated instead of unique as this returns logicals you can use to index l and keep the names

l[!duplicated(l)]

Upvotes: 4

Related Questions