# [BioC] makeContrasts in limma

Gordon K Smyth smyth at wehi.EDU.AU
Wed Jun 8 01:13:19 CEST 2005

```It is true that makeContrasts() doesn't accept character-valued variables.  E.g.,

> makeContrasts("A-B",levels=c("A","B"))
> makeContrasts(A-B,levels=c("A","B"))

will both work but

> x <- "A-B"
> makeContrasts(x,levels=c("A","B"))

will not.  I will have a think about how this might be fixed.

To compute a design matrix to make all possible pairwise comparisons, it is easier to do this
directly.  Here is a little function which does the job:

> design.pairs <-
function(levels) {
n <- length(levels)
design <- matrix(0,n,choose(n,2))
rownames(design) <- levels
colnames(design) <- 1:choose(n,2)
k <- 0
for (i in 1:(n-1))
for (j in (i+1):n) {
k <- k+1
design[i,k] <- 1
design[j,k] <- -1
colnames(design)[k] <- paste(levels[i],"-",levels[j],sep="")
}
design
}
> design.pairs(c("A","B","C","D"))
A-B A-C A-D B-C B-D C-D
A   1   1   1   0   0   0
B  -1   0   0   1   1   0
C   0  -1   0  -1   0   1
D   0   0  -1   0  -1  -1

Gordon

> Date: Mon, 6 Jun 2005 18:22:11 -0400
> From: "He, Yiwen (NIH/CIT)" <heyiwen at mail.nih.gov>
> Subject: [BioC] makeContrasts in limma
> To: "'bioconductor at stat.math.ethz.ch'"
> 	<bioconductor at stat.math.ethz.ch>
>
> Hi,
> In limma, what is the best way to automatically generate a contrast matrix
> with all possible pairs? For example, if I have 4 groups, is there a way to
> generate the matrix with 6 columns each corresponding to a pair-wise
> comparison, other than having to specify the 6 expressions explicitly when
> calling makeContrasts?
>
> I tried to first create a vector with those expressions and use that in
> makeContrasts:
>
>> pair<-c()
>> ind<-1
>> for (i in 2:numg){
> + for (j in i:numg) {
> + pair[ind] <- paste(groupname[j], "-", groupname[(j-i+1)])
> + ind<- ind+1}}
>> pair
> [1] "GroupB - GroupA" "GroupC - GroupB" "GroupC - GroupA"
>
>> makeContrasts(pair, levels=design)
>        pair
> GroupA "GroupB - GroupA"
> GroupB "GroupC - GroupB"
> GroupC "GroupC - GroupA"
>
> A related problem: I noticed that expressions have to be separated by comma.
> However, even when I tried:
>
>> makeContrasts(pair[1], levels=design)
>        pair[1]
> GroupA "GroupB - GroupA"
> GroupB "GroupB - GroupA"
> GroupC "GroupB - GroupA"
>
> Compare to the result by doing:
>> pair[1]
> [1] "GroupB - GroupA"
>> makeContrasts("GroupB - GroupA", levels=design)
>        GroupB - GroupA
> GroupA              -1
> GroupB               1
> GroupC               0
>
> The help page says:
> "...: expressions, or character strings which can be parsed to expressions"
>
> But my string doesn't seem to be converted.
>
> Any suggestions? Will it be more convenient to use if the ... argument is a
> vector of expressions or something similar?
>
> Thank you, Yiwen
> NIH/CIT

```