简体   繁体   中英

matrix of matrices (as a list) in R

Suppose I have 3 matrices C , W , and S

C <- matrix(1:3)
W <- matrix(2:4)
S <- matrix(3:5)

I want to make a matrix with those matrices as elements. Say matrix K , but each element of matrix K being a matrix itself. Just as a list of matrices works, but instead in a matrix form. Ie:

> K
      [,1] [,2] [,3]
[1,]    C    0   0
[2,]    0    W   S

C , W and S would each be matrix objects stored inside the larger matrix K .

Ultimately, I would like to be able to then use matrix multiplication like K %*% K or similar.

There are not a lot of classes than can be an element in an R matrix. In particular objects that rely on attributes for their behavior cannot be objects that will retain their essential features. And ironically that includes matrices themselves since their behavior is governed by the dim(ension) attribute. That exclusion applies to dates, factors and specialized lists such as dataframes. You can include lists as index-able items in a matrix, but as @thelatemail's comment points out this will be somewhat clunky.

> C <- matrix(0, 3,2)
> W <- matrix(1, 4,5)
> S <- matrix(2, 6,7)
> bigM <- matrix( list(), 2, 3)
> bigM[1,1] <- list(C)
> bigM[2,2] <- list(W)
> bigM[2,3] <- list(S)
> bigM
     [,1]      [,2]       [,3]      
[1,] Numeric,6 NULL       NULL      
[2,] NULL      Numeric,20 Numeric,42
> bigM[2,3][[1]][42]
[1] 2

Notice the need to extract the matrix itself with [[1]] after extracting it as a list with [2,3] . It's only after that additonal step thay you can get the 42nd item in the matrix, whould alos have been the [6,7] th item if you chose to reference it by row,column indices.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM