Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get unique element from a vector, keeping its name? [duplicate]

Tags:

r

unique

subset

I know there is the function unique() that extracts the unique values from a vector. But I lose its name.

Ex.

vector = c("A" = 1, "B" = 2, "A" = 1, "C" = 3, "B" = 2, "D" = 3, "D" = 3)

If I print I should see:

A B A C B D D
1 2 1 3 2 3 3

Expected output:

A B C D
1 2 3 3

Attempts:

If I use: unique(vector) I only get 1 2 3

If I use: vector[!duplicated(vector)] I get:

A B C 
1 2 3 

This is close, but the "D" = 3 is missing.

like image 886
Saul Garcia Avatar asked Mar 10 '17 08:03

Saul Garcia


2 Answers

vector = c(A=1,B=2,A=1,C=3,B=2,D=3,D=3)

When you do,

vector[!duplicated(vector)]

it looks for duplicates in values of vector and not names hence the output which you get is

A B C 
1 2 3 

If you want to find unique names then you should run duplicated function on the names of the vector

vector[!duplicated(names(vector))]

A B C D 
1 2 3 3 

Also similar ouptut could be achieved using unique

vector[unique(names(vector))]

A B C D 
1 2 3 3 
like image 104
Ronak Shah Avatar answered Sep 25 '22 23:09

Ronak Shah


Just to add another alternative that also may cover discripancy between values and names

library(dplyr)
data_frame(value = v, name = names(v)) %>%
  group_by(name, value) %>% # alternatively: group_by(name) if name value pair is always unique
  slice(1) %>%
  ungroup()
like image 26
Drey Avatar answered Sep 22 '22 23:09

Drey