DonDyck DonDyck - 14 days ago 7
R Question

Find pairs of elements for duplicated values in a vector - R

I have a vector with some of the elements repeated. I want to list all the pairs of indices with equal values.

i.e. given input

x <- c(1,2,3,2,4,3,2)


I want to generate the list

duplicate_x <- [[2,4,7],[3,6]]


How to solve this in R

Answer
dups = duplicated(x) | duplicated(x, fromLast = T)

split(which(dups), x[dups])
#$`2`
#[1] 2 4 7
#
#$`3`
#[1] 3 6
Comments