Here is my toy dataframe, the real one might have 40K-1M records and five additional columns
animal1 version1 animal2 version2 sim
53 20154620 TRUSEQ.v1 20104647 F250v1 0.3663569
854 20145687 TRUSEQ.v1 20105551 F250v1 0.5732854
3662 20154620 TRUSEQ.v1 20114509 F250v1 0.3374918
4063 20154620 TRUSEQ.v1 20114578 F250v1 0.3732692
4464 20154620 TRUSEQ.v1 20114595 F250v1 0.3772367
5262 20144516 TRUSEQ.v1 20115051 770k.v1 0.6034206
5663 20144516 TRUSEQ.v1 20115051 F250v1 0.6164795
5664 20145008 TRUSEQ.v1 20115051 F250v1 0.3146651
6064 20144516 TRUSEQ.v1 20115059 F250v1 0.3043295
6471 20165119 F250v1 20115096 F250v1 0.388435
9677 20154620 TRUSEQ.v1 20118095 F250v1 0.3079702
11281 20154620 TRUSEQ.v1 20134529 F250v1 0.3188631
12486 20165119 F250v1 20135032 F250v1 0.6091486
13282 20144516 TRUSEQ.v1 20135047 F250v1 0.3098507
14090 20165119 F250v1 20135072 F250v1 0.3025007
14892 20165119 F250v1 20135122 F250v1 0.345238
For each animal1, I need all rows featuring the top 3 unique animal2 values by highest sim... so my desired result is reproduced below.
animal1 version1 animal2 version2 sim
5663 20144516 TRUSEQ.v1 20115051 F250v1 0.6164795
5262 20144516 TRUSEQ.v1 20115051 770k.v1 0.6034206
13282 20144516 TRUSEQ.v1 20135047 F250v1 0.3098507
6064 20144516 TRUSEQ.v1 20115059 F250v1 0.3043295
5664 20145008 TRUSEQ.v1 20115051 F250v1 0.3146651
854 20145687 TRUSEQ.v1 20105551 F250v1 0.5732854
4464 20154620 TRUSEQ.v1 20114595 F250v1 0.3772367
4063 20154620 TRUSEQ.v1 20114578 F250v1 0.3732692
53 20154620 TRUSEQ.v1 20104647 F250v1 0.3663569
12486 20165119 F250v1 20135032 F250v1 0.6091486
6471 20165119 F250v1 20115096 F250v1 0.388435
14892 20165119 F250v1 20135122 F250v1 0.345238
So in the subset, each animal1 might have between 1 and 20 observations but will have <=n unique values of animal2 where n=3 in this case.
I can sort the df by sim and animal1 like this
mydf <- mydf[order(-xtfrm(mydf[,"animal1"]), -mydf[,"sim"]),]
I can grab the first n observations per animal1 like this
mydf2 <- by(mydf, mydf["animal1"], head, n=1)
mydf2 <- Reduce(rbind, mydf2)
But how do I apply n to a third column, animal2 rather than the number of observations? Apologies if this is a duplicate, the answer is probably hidden in here, how to find the top N values by group or within category (groupwise) in an R data.frame but I just can't seem to stitch together a solution to my problem from the answers.