Calculate Pairwise Distance from a Matrix

dist2(x, pairwise_fun = function(x, y) sqrt(sum((x - y)^2)), ...)

Arguments

x

A matrix or a list. If it is a matrix, the distance is calculated by rows.

pairwise_fun

A function which calculates distance between two vectors.

...

Pass to as.dist.

Details

You can construct any type of distance measurements by defining a pair-wise distance function. The function is implemented by two nested for loops, so the efficiency may not be so good.

Value

A dist object.

Examples

lt = lapply(1:10, function(i) { sample(letters, sample(6:10, 1)) }) dist2(lt, function(x, y) { length(intersect(x, y))/length(union(x, y)) })
#> 1 2 3 4 5 6 7 #> 2 0.26666667 #> 3 0.15384615 0.14285714 #> 4 0.12500000 0.26666667 0.25000000 #> 5 0.14285714 0.41666667 0.08333333 0.33333333 #> 6 0.20000000 0.35714286 0.07142857 0.20000000 0.45454545 #> 7 0.38461538 0.26666667 0.07142857 0.28571429 0.14285714 0.12500000 #> 8 0.20000000 0.18750000 0.15384615 0.12500000 0.06666667 0.20000000 0.20000000 #> 9 0.05882353 0.18750000 0.15384615 0.28571429 0.33333333 0.12500000 0.05882353 #> 10 0.28571429 0.26666667 0.15384615 0.28571429 0.14285714 0.12500000 0.28571429 #> 8 9 #> 2 #> 3 #> 4 #> 5 #> 6 #> 7 #> 8 #> 9 0.12500000 #> 10 0.12500000 0.28571429