R: List of indices, including empty ones, to binary matrix -
say have list of indices, including elements empty, like:
l <- list(c(1,2,3), c(1), c(1,5), null, c(2, 3, 5)) which specify non-zero elements in matrix, like:
(m <- matrix(c(1,1,1,0,0, 1,0,0,0,0, 1,0,0,0,5, 0,0,0,0,0, 0,1,1,0,1), nrow=5, byrow=true)) [,1] [,2] [,3] [,4] [,5] [1,] 1 1 1 0 0 [2,] 1 0 0 0 0 [3,] 1 0 0 0 5 [4,] 0 0 0 0 0 [5,] 0 1 1 0 1 what fastest way, using r, make m l, giving matrix big, 50.000 rows , 2000 columns?
you can filter non-null list elements 'l' , use melt reshape 'data.frame' 'key/value' columns or `row/column' index columns.
library(reshape2) d2 <- melt(filter(negate(is.null), setnames(l, seq_along(l)))) un1 <- unlist(l) m1 <- matrix(0, nrow=length(l), ncol=max(un1)) m1[cbind(as.numeric(d2[,2]), d2[,1])] <- 1 m1 # [,1] [,2] [,3] [,4] [,5] #[1,] 1 1 1 0 0 #[2,] 1 0 0 0 0 #[3,] 1 0 0 0 1 #[4,] 0 0 0 0 0 #[5,] 0 1 1 0 1 or
library(matrix) as.matrix(sparsematrix(as.numeric(d2[,2]), d2[,1], x=1)) # [,1] [,2] [,3] [,4] [,5] #[1,] 1 1 1 0 0 #[2,] 1 0 0 0 0 #[3,] 1 0 0 0 1 #[4,] 0 0 0 0 0 #[5,] 0 1 1 0 1
Comments
Post a Comment