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:
> 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)