Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compute all pairwise differences within a vector in R

Tags:

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?

like image 745
colin Avatar asked Jun 19 '14 19:06

colin


People also ask

How do you find the pairwise comparison?

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.

How do you calculate pairwise?

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.

What is pairwise r?

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).

What pairwise comparisons show?

Pairwise comparisons are methods for analyzing multiple population means in pairs to determine whether they are significantly different from one another.


1 Answers

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.

like image 146
Ben Bolker Avatar answered Oct 03 '22 08:10

Ben Bolker