Tan Eugene
Tan Eugene

Reputation: 93

R Code: List containing column numbers to increment

I am having a list containing the column numbers:

list = list(c(1,4,5),c(2,4,2))
matrix = matrix(rep(0,10),ncol=5)

> list
[[1]]
[1] 1 4 5

[[2]]
[1] 2 4 2


> matrix
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0

What I would want to achieve is:

> matrix
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    0    1    1
[2,]    0    1    0    1    0

But because my list is huge and my matrix is huge, I am not satisfied with looping through:

for (i in 1:length(list)) matrix[i,list[[i]]] = 1

Upvotes: 1

Views: 57

Answers (1)

akrun
akrun

Reputation: 887128

We can try sparseMatrix from library(Matrix)

library(Matrix)
sM <- sparseMatrix(i= rep(seq_along(list), lengths(list)), 
                    j= unlist(list),
                    x= 1)
as.matrix(sM)

Not sure the column numbers that were repeated in the same list element is typo or not. If it is not a typo, and still want the binary output

+(!!(as.matrix(sM)))
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    1    0    0    1    1
#[2,]    0    1    0    1    0

Upvotes: 2

Related Questions