简体   繁体   English

R中的矩阵矩阵(作为列表)

[英]matrix of matrices (as a list) in R

Suppose I have 3 matrices C , W , and S假设我有 3 个矩阵CWS

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.说矩阵K ,但矩阵的每个元素K是一个矩阵本身。 Just as a list of matrices works, but instead in a matrix form.就像矩阵列表一样工作,而是以矩阵形式。 Ie: 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 . CWS都是存储在较大矩阵K矩阵对象。

Ultimately, I would like to be able to then use matrix multiplication like K %*% K or similar.最终,我希望能够使用矩阵乘法,如K %*% K或类似的。

There are not a lot of classes than can be an element in an R matrix.没有很多类可以作为 R 矩阵中的元素。 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.您可以将列表作为可索引项目包含在矩阵中,但正如@thelatemail 的评论指出的那样,这会有些笨拙。

> 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] .请注意,在使用[2,3]其提取为列表后,需要使用[[1]]提取矩阵本身。 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.只有在该附加步骤之后,您才能获得矩阵中的第 42 项,如果您选择按row,column索引引用它,也应该是第[6,7]项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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