Spearman's footrule distance with base R

2019-07-12 16:01发布

问题:

Given two permutations:

v1
[1] 4 3 1 5 2

v2
[1] 2 3 4 5 1

How do you compute the Spearman's footrule distance (total displacement of all elements) with base R? (flexible for any two permutations of size n)

For example, for these two vectors, it's as follows:

1 is moved 2 places from v1 to v2
2 is moved 4 places from v1 to v2
3 is moved 0 places from v1 to v2
4 is moved 2 places from v1 to v2
5 is moved 0 places from v1 to v2

So the total distance would be: 2+4+0+2+0 = 8

回答1:

Here is a method using sapply, which, and sum:

sum(sapply(seq_along(v1), function(i) abs(i - (which(v2 == v1[i])))))

Here, we move along the indices of v1 and calculate the distance of the index of the element in the current index from its position in v2. These are then summed together.

I suspect something along the lines of @alexis_laz's solution in the comments may have greater computational efficiency.