There are several posts on computing pairwise differences among vectors, but I cannot find how to compute all differences within a vector.
Say I have a vector, v.
v<-c(1:4)
I would like to generate a second vector that is the absolute value of all pairwise differences within the vector. Similar to:
abs(1-2) = 1 abs(1-3) = 2 abs(1-4) = 3 abs(2-3) = 1 abs(2-4) = 2 abs(3-4) = 1
The output would be a vector of 6 values, which are the result of my 6 comparisons:
output<- c(1,2,3,1,2,1)
Is there a function in R that can do this?
Complete Pairwise Comparison You can calculate the total number of pairwise comparisons using a simple formula: n(n-1)/2 , where n is the number of options. For example, if we have 20 options, this would be 20(19)/2 → 380/2 → 190 pairs.
The formula for the number of independent pairwise comparisons is k(k-1)/2, where k is the number of conditions. If we had three conditions, this would work out as 3(3-1)/2 = 3, and these pairwise comparisons would be Gap 1 vs.
The pairwise function transforms data given in an arm-based format into the contrast-based format which is needed as input to R function netmeta . The pairwise functions expects a number of lists as mandatory input depending on the type of data (see next paragrah).
Pairwise comparisons are methods for analyzing multiple population means in pairs to determine whether they are significantly different from one another.
as.numeric(dist(v))
seems to work; it treats v
as a column matrix and computes the Euclidean distance between rows, which in this case is sqrt((x-y)^2)=abs(x-y)
If we're golfing, then I'll offer c(dist(v))
, which is equivalent and which I'm guessing will be unbeatable.
@AndreyShabalin makes the good point that using method="manhattan"
will probably be slightly more efficient since it avoids the squaring/square-rooting stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With