Replacing singular values with lists in a matrix
matrix, r, replace
Solution
Since the dimension of the result is different (a 3-dimensional array instead of a 2-dimensional matrix), you cannot just replace the elements one by one.
You can use `apply`: if is often used to apply a function to each column or row of a matrix, but we can also use it to apply a function to each element.
apply(
test,
1:2,
function(u) list(c(0,0,0), c(0,0,1), c(0,1,0), c(1,0,1))[[u+1]]
)
Problem
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 with 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?