7

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Saul Garcia
  • 890
  • 2
  • 9
  • 22

3 Answers3

6
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 
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
2

We can use match

vector[match(unique(names(vector)), names(vector))]
# A B C D 
# 1 2 3 3 

or with tapply

tapply(vector, names(vector), FUN = head, 1)
#  A B C D 
# 1 2 3 3 

Or using data.table

library(data.table)
data.table(Key = names(vector), Value = c(vector))[, Value[1L], Key]
akrun
  • 874,273
  • 37
  • 540
  • 662
2

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()
Drey
  • 3,314
  • 2
  • 21
  • 26