rglmglmnetmodel.matrix

How to generate a specific design matrix in R?


I want to create a design matrix for use in the glmnet function. My predictors are player names; when player i plays a match against player j I want the row for that match to have a +1 in column i and a -1 in column j.

For example, if there are three players who all play each other, the design matrix should be as follows:

1 -1  0
1  0 -1 
0  1 -1 

I've tried using model.matrix but I'm not sure how to create this specific design matrix - alternatively if there's a better format for this matrix that would also be helpful to know!


Solution

  • Try this:

    num_players <- 4
    matches <- t(combn(num_players, 2))
    nr <- nrow(matches)
    
    mtx <- matrix(0L, nrow = nr, ncol = num_players)
    mtx[ cbind(seq_len(nr), matches[,1]) ] <- 1L
    mtx[ cbind(seq_len(nr), matches[,2]) ] <- -1L
    mtx
    #      [,1] [,2] [,3] [,4]
    # [1,]    1   -1    0    0
    # [2,]    1    0   -1    0
    # [3,]    1    0    0   -1
    # [4,]    0    1   -1    0
    # [5,]    0    1    0   -1
    # [6,]    0    0    1   -1