vector - Spearman's footrule distance with base R -
given 2 permutations:
v1 [1] 4 3 1 5 2 v2 [1] 2 3 4 5 1 how compute spearman's footrule distance (total displacement of elements) base r? (flexible 2 permutations of size n)
for example, these 2 vectors, it's follows:
1 moved 2 places v1 v2
2 moved 4 places v1 v2
3 moved 0 places v1 v2
4 moved 2 places v1 v2
5 moved 0 places v1 v2
so total distance be: 2+4+0+2+0 = 8
here method using sapply, which, , sum:
sum(sapply(seq_along(v1), function(i) abs(i - (which(v2 == v1[i]))))) here, move along indices of v1 , calculate distance of index of element in current index position in v2. these summed together.
i suspect along lines of @alexis_laz's solution in comments may have greater computational efficiency.
Comments
Post a Comment