# [R] pairwise difference operator

From: Adaikalavan Ramasamy <ramasamy_at_cancer.org.uk>
Date: Sat 31 Jul 2004 - 09:30:52 EST

I tried unsuccessfully with the apply() family. Searching the mailing list was not very fruitful either. The closest I got to was a cryptic chunk of code in pairwise.table().

Since I do use something similar myself occasionally, I am hoping someone from the R-help list can suggest alternatives or past threads. Thank you.

### Code ###

pairwise.difference <- function(m){

```  npairs  <- choose( ncol(m), 2 )
results <- matrix( NA, nc=npairs, nr=nrow(m) )
cnames  <- rep(NA, npairs)
```

if(is.null(colnames(m))) colnames(m) <- paste("col", 1:ncol(m), sep="")

k <- 1
for(i in 1:ncol(m)){
for(j in 1:ncol(m)){

```      if(j <= i) next;
results[ ,k] <- m[ ,i] - m[ ,j]
cnames[k]    <- paste(colnames(m)[ c(i, j) ], collapse=".vs.")
k <- k + 1
```

}
}

colnames(results) <- cnames
rownames(results) <- rownames(m)
return(results)
}

A B C D
g1 10 16 3 15
g2 18 5 12 19
g3 7 4 8 13
g4 14 2 6 11
g5 17 1 20 9

pairwise.difference(mat)

A.vs.B A.vs.C A.vs.D B.vs.C B.vs.D C.vs.D

```g1     -6      7     -5     13      1    -12
g2     13      6     -1     -7    -14     -7
g3      3     -1     -6     -4     -9     -5
g4     12      8      3     -4     -9     -5
g5     16     -3      8    -19     -8     11

```

Regards,

```--