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?
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.