Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get indexes of up to n first occurrences of each unique value in vector

Let’s say I have this vector:

v=c(1,1,1,1,2,2,2,3,3,3)

How can I return the indexes of the first two occurrences of each distinct value? I only found this really convoluted way:

> (data.frame(v=v,n=1:length(v))%>%group_by(v)%>%slice_max(v,n=2,with_ties=F))[,2]%>%unlist%>%unname
[1] 1 2 5 6 8 9

And this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

> seen=setNames(numeric(length(unique(v))),unique(v))
> o=c();n=1;for(i in v){x=as.character(i);s=seen[x];if(s<2){o[n]=i;n=n+1};seen[x]=s+1};o
[1] 1 2 5 6 8 9

>Solution :

We can use tapply in base R, use ‘v’ as the grouping and the input as sequence of ‘v’, get the first two with head, unlist the list and unname it

unname(unlist(tapply(seq_along(v), v, head, 2)))
[1] 1 2 5 6 8 9

Or split by ‘v’, get the head by looping over the list with sapply

c(sapply(split(seq_along(v), v), head, 2))
[1] 1 2 5 6 8 9

Or slightly compact option with rowid

library(data.table)
seq_along(v)[rowid(v) < 3]
[1] 1 2 5 6 8 9

Or as @Henrik mentioned, use which directly

which(rowid(id) < 3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading