Extract elements from a vector that are repeated n times (R)

Viewed 299

I will try to make my point. Imagine I've got a vector with an unknown length and/or content like the next one:

col.vector = c(1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 5, 5)

I want to extract all the elements that are repeated "n" times. Lets say 3 times, then I want to be returned a vector with the respective elements: c(3, 4).

Is there any simple function?

3 Answers

One option could be:

with(rle(col.vector), values[lengths == 3])

[1] 3 4

We can use table if it is based on frequency

v1 <- table(col.vector)
as.integer(names(v1)[v1 == 3])
[1] 3 4

If it is based on repeating elements, use rleid

library(data.table)
v1 <- table(rleid(col.vector))
as.integer(names(v1)[v1 == 3])

Another way with table -

n <- 3
names(Filter(function(x) x == n, table(col.vector)))
#[1] "3" "4"
Related