Home > database >  How to assign matrix elements to indices in a list in R?
How to assign matrix elements to indices in a list in R?

Time:04-19

I want to do something like this:

A = matrix(0, nrow = 3, ncol = 8)
for (ind in list(c(1,2), c(2,3), c(1,6), c(2,7), c(3,8))){
  # print(ind)
  A[ind] = 1
  }

Printing ind gives me what I expect (line 1, 2 then 2,3 and so on), but after running this loop A is:

> A
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    1    0    1    0    0    0    0    0
[2,]    1    0    1    0    0    0    0    0
[3,]    1    1    0    0    0    0    0    0

and I have really no idea why.

CodePudding user response:

You could do:

A[do.call(`rbind`, lst)] <- 1

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    1    0    0    0    1    0    0
[2,]    0    0    1    0    0    0    1    0
[3,]    0    0    0    0    0    0    0    1

CodePudding user response:

Another option, same premise.

A <- matrix(0, nrow = 3, ncol = 8)
lst <- list(c(1,2), c(2,3), c(1,6), c(2,7), c(3,8))

A[t(list2DF(lst))] <- 1
A
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8]
[1,]    0    1    0    0    0    1    0    0
[2,]    0    0    1    0    0    0    1    0
[3,]    0    0    0    0    0    0    0    1

To answer your question of why the loop will not work, you need to transpose the index.

A = matrix(0, nrow = 3, ncol = 8)
for (ind in list(c(1,2), c(2,3), c(1,6), c(2,7), c(3,8))){
  # print(ind)
  A[t(ind)] = 1
}
  •  Tags:  
  • r
  • Related