8

I would like to keep the non-duplicated values from a vector, but without retaining one element from duplicated values. unique() does not work for this. Neither would duplicated().

For example:

> test <- c(1,1,2,3,4,4,4,5,6,6,7,8,9,9)
> unique(test)
[1] 1 2 3 4 5 6 7 8 9

Whereas I would like the result to be: 2,3,5,7,8

Any ideas on how to approach this? Thank you!

arielle
  • 915
  • 1
  • 12
  • 29

2 Answers2

11

We can use duplicated

test[!(duplicated(test)|duplicated(test, fromLast=TRUE))]
#[1] 2 3 5 7 8
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 1
    imo this should have received the tick - much better to work with vectors where possible, rather than splitting and looping – user20650 Mar 10 '17 at 22:41
9

You can use ave to count the length of sub-groups divided by unique values in test and retain only the ones whose length is 1 (the ones that have no duplicates)

test[ave(test, test, FUN = length) == 1]
#[1] 2 3 5 7 8

If test is comprised of characters, use seq_along as first argument of ave

test[ave(seq_along(test), test, FUN = length) == 1]
d.b
  • 32,245
  • 6
  • 36
  • 77