Fuv8
Fuv8

Reputation: 905

Check for unique elements

just a simple question. I have a data frame(only one vector is shown) that looks like:

cln1
A
b
A
A
c
d
A
....

I would like the following output:

cln1
b
c
d

In other words I would like to remove all items that are replicated. The functions "unique" as well as "duplicated" return the output including the replicated element represented one time. I would like to remove it definitively.

Upvotes: 4

Views: 221

Answers (3)

Arun
Arun

Reputation: 118799

Another way using table:

With @juba's data:

as.numeric(names(which(table(v) == 1)))
# [1] 3 4 5

For OP's data, since its a character output, as.numeric is not required.

names(which(table(v) == 1))
# [1] "b" "c" "d"

Upvotes: 2

Paul Hiemstra
Paul Hiemstra

Reputation: 60934

You could use count from the plyr package to count the occurences of an item, and delete all who occur more than once.

library(plyr)
l = c(1,2,3,3,4,5,6,6,7)
count_l = count(l)
  x freq
1 1    1
2 2    1
3 3    2
4 4    1                                                                           
5 5    1                                                                           
6 6    2                                                                           
7 7    1  
l[!l %in%  with(count_l, x[freq > 1])]
[1] 1 2 4 5 7  

Note the !, which means NOT. You of course put this in a oneliner:

l[!l %in%  with(count(l), x[freq > 1])]

Upvotes: 5

juba
juba

Reputation: 49033

You can use setdiff for that :

R> v <- c(1,1,2,2,3,4,5)
R> setdiff(v, v[duplicated(v)])
[1] 3 4 5

Upvotes: 9

Related Questions