alittleboy
alittleboy

Reputation: 10956

find the ranks of elements in a vector from another longer vector in R

Suppose I have a short vector v1=c(1,3,4,7,9) and another short vector v2=c(3,4,10,12,9). The combined "long" vector is v=c(1,3,3,4,4,7,9,9,10,12). Now I want to find the rank of each of the elements in v1 (i.e. 1,3,4,7,9) in the long vector v. How can I efficiently do that in R? Thanks!

Upvotes: 0

Views: 313

Answers (1)

thelatemail
thelatemail

Reputation: 93813

How about this?

sapply(v1,function(x) mean(which(x==v)))
# [1] 1.0 2.5 4.5 6.0 7.5

Upvotes: 1

Related Questions