# 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! ______________________________________________ R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.