Spearman's footrule distance with base R

£可爱£侵袭症+ 提交于 2019-12-24 00:29:29

问题


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.



来源:https://stackoverflow.com/questions/38328325/spearmans-footrule-distance-with-base-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!