Skip to Content

Replacing singular values by lists in a matrix

Given the matrix

test <- structure(list(X1 = c(3L, 0L, 3L, 1L, 2L, 2L, 1L, 2L, 2L, 3L), 
X2 = c(2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), X3 = c(0L, 
0L, 3L, 0L, 2L, 2L, 3L, 0L, 0L, 2L), X4 = c(1L, 1L, 1L, 0L, 
3L, 1L, 3L, 1L, 1L, 1L), X5 = c(3L, 3L, 1L, 3L, 1L, 3L, 2L, 
3L, 3L, 3L), X6 = c(3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L
), X7 = c(2L, 2L, 2L, 3L, 2L, 2L, 3L, 2L, 2L, 2L), X8 = c(3L, 
0L, 1L, 0L, 1L, 1L, 3L, 0L, 0L, 1L), X9 = c(3L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L)), .Names = c("X1", "X2", "X3", "X4", 
"X5", "X6", "X7", "X8", "X9"), row.names = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10"), class = "data.frame")

I'm trying to replace each instance of "1" by the sequence of numbers c(0,0,1), 2 by c(0,1,0), 3 by (1,0,1), and 0 by (0,0,0). Each value in the matrix should be replaced by one of these sequences of three binary values. The nrow of the resulting matrix should be nrow(test) * 3. Obviously I tried to use indexes test[test == 1] <- c(0,0,1) but this returns error rhs is the wrong length for indexing by a logical matrix. The replace function also doesn't seem to work here, returning the same error message. Any idea?