Removing values ​​from a vector that is not duplicated at least x times

For the vector:

eg:.

a = c(1, 2, 2, 4, 5, 3, 5, 3, 2, 1, 5, 3)

Using a[a%in%a[duplicated(a)]], I can remove values ​​that are not duplicated. However, it only works for values ​​that are present only once.

How can I continue deleting all values ​​that are not present in this three times? (or more, in other situations)

Expected Result:

2 2 5 3 5 3 2 5 3

with the removal of 1 and 4, since they are present only twice and once

+4
source share
2 answers

You can do this on one line using the function ave:

a[ave(a, a, FUN=length) >= 3]
# [1] 2 2 5 3 5 3 2 5 3

ave(a, a, FUN=length) a[i] a, a[i] a. a, , 3 .

+8

(, ave, , , ):

x <- c(1,2,2,4,5,3,5,3,2,1,5,3)
tt <- table(x)   ## tabulate
## find relevant values
ttr <- as.numeric(names(tt)[tt>=3])
x[x %in% ttr]  ## subset
+5

All Articles