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.
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With