[R] Expanding matrix into dummies
Dimitri Liakhovitski
dimitri.liakhovitski at gmail.com
Tue Dec 22 23:42:51 CET 2015
# I have a matrix x:
k <- 20
N <- 5
set.seed(123)
x <- matrix(c(sample(1:k, N, replace = F),
sample(1:k, N, replace = F),
sample(1:k, N, replace = F),
sample(1:k, N, replace = F),
sample(1:k, N, replace = F),
sample(1:k, N, replace = F)), byrow = T, ncol = 5)
colnames(x) <- paste0("column", 1:5)
(x)
# I want to reshape it into a matrix 'result' with k columns (not N).
# 'result' should contain the same number of rows as x, and it should have
# in each row 1s in those columns that correspond to the entries in x
in the same row.
# For example, the first row of 'result' should contain 1s in columns
6, 8, 15, 16, and 17, etc.
# The remaining entries should be zeros.
result <- matrix(rep(0, nrow(x) * k), nrow = nrow(x))
colnames(result) <- paste0("item", 1:k)
# I can see how to do it by looping through rows of result.
# But I need to do it fast (not using a loop).
# I feel like I should subset 'result' with 'x', but I am not sure how.
Thank you very much!
More information about the R-help
mailing list