find the first element that has repeated N times in R

Viewed 138

I need to find the first element that repeated "N" times, and "N" may change. For example, the elements are:

test <- c("A","B","B","C","A","A","C","C","C")

If N=2, it should return "B".

If N=3, it should return "A".

I have seen similar questions, but I need to only return the first element which repeated "N" times, and then stop. Many thanks.

(I made this example to represent a real work problem in an experimental chemistry study, where we have to find the re-occurrence of something.But the numbers of re-occurrence to be considered always change! Thanks!)

2 Answers

One option using data.table could be:

fun <- function(x) {test[which.max(rowid(test) == x)]}

fun(2)

[1] "B"

fun(3)

[1] "A"

fun(4)

[1] "C"

Or the same idea with just base R:

fun <- function(x) {test[which.max(ave(test, test, FUN = seq_along) == x)]}

A fun way, probably a lot slower than tmfmnk's ave(... seq_along...) approach

foo <- rle(sort(text)) 

Then if N appears more than once in foo$lengths ,

items <- foo$values[which(foo$lengths == N)] 

Then for all values in items, grab min(which(text==items[k]) and the smallest value you get will tell you the character that shows up first and occurs N times.

Related