rmatrix

create a matrix of 0s and 1s based on vector labels


I have a vector:

A <- c("CTRL", "A", "B", "C")

I would like to generate this matrix:

             [A]   [B]  [C] [CTRIL
[A-CTRL]      1     0.   0.   -1
[B-CTRL]      0.    1.   0.   -1
[C-CTRL]      0.    0.   1.   -1

I did write something like this:

levels(global.proteinSummarization$ProteinLevelData$GROUP)

comparison1 <- matrix(c(1,-1,0,0,0,0,0,0), nrow=1)
comparison2 <- matrix(c(0,-1,1,0,0,0,0,0), nrow=1)
comparison3 <- matrix(c(0,-1,0,1,0,0,0,0), nrow=1)

comparison <- rbind(comparison1, comparison2, comparison3)
row.names(comparison) <- c("A-CTRL", "B-CTRL", "C-CTRL")
colnames(comparison) <- levels(global.proteinSummarization$ProteinLevelData$GROUP) 

However, is there any more automatic way?


Solution

  • You can produce a "sum to zero" contrast matrix.

    t(contr.sum(c("A", "B", "C", "CTRL")))
    
    #      A B C CTRL
    # [1,] 1 0 0   -1
    # [2,] 0 1 0   -1
    # [3,] 0 0 1   -1