2

I know I can get the index of duplicates using duplicated in R. But I wonder how to get the index of all instances of a duplicate in the entire vector?

As a trivial example, if 1, 7 are duplicates, how to get the indices of theses values all over the vector?

a = c(1, 7, 5, 7, 4, 1)

duplicated(a)

Desired output:

c(T, T, F, T, F, T)
thelatemail
  • 91,185
  • 12
  • 128
  • 188

2 Answers2

3

You can do:

duplicated(a) | duplicated(a, fromLast = TRUE)

[1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE
tmfmnk
  • 38,881
  • 4
  • 47
  • 67
  • Could you please tell me what the difference it made by adding `fromLast` argument? – Daman deep Sep 30 '21 at 04:41
  • 1
    @Daman deep `fromLast = TRUE` looks for duplicates from the opposite direction. That is, from the last element of the vector to the first one. – tmfmnk Sep 30 '21 at 14:16
0

An option with table

(table(a) > 1)[as.character(a)]

Or using ave

ave(a, a, FUN = length) > 1
akrun
  • 874,273
  • 37
  • 540
  • 662