R:如何操作列表中的矩阵?

问题描述 投票:1回答:1

我是R新用户,现在使用mapply命令在矩阵之间进行操作;我最初的问题有两个列表,每个列表有30个矩阵。但是,为了更好地解释我的问题,我将仅使用6个矩阵。

Phi1<-matrix(1:9, ncol = 3)
Phi2<-matrix(10:18, ncol = 3)
Phi3<-matrix(0:-8, ncol = 3)

mat <- matrix(1:24, ncol = 3)
p <- 3 
m <- 5 
mat_df <- as.data.frame(mat)
mat_lag <- map(1:p, ~ mutate_all(mat_df, lag, .x)) %>% 
map(drop_na) %>% 
map(~ slice(.x, (nrow(.x) - m + 1):nrow(.x)))
mat_lag %>% 
map(as.matrix)
PHI<-list(Phi1, Phi2, Phi3)

我的想法是将PHI(i)的元素乘以mat_lag[[i]]

Example<-mapply(function(x, y) x*y,  t(Phi1), mat_lag[[1]])

问题是,在最初的问题中,我有30个矩阵,并且我不想手动提取列表中的每个元素。通过上面的命令,我得到了所需的结果,如下所示:

     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]   23  147  319   27  159  339   31  171  359
[2,]   34  161  336   39  174  357   44  187  378
[3,]   45  175  353   51  189  375   57  203  397
[4,]   56  189  370   63  204  393   70  219  416
[5,]   67  203  387   75  219  411   83  235  435

但是,我不明白如何将此命令应用于列表,这样我的最终结果将是30个矩阵大小为5 * 9的列表

r list
1个回答
0
投票

不是最优雅的(30个矩阵可能会很慢):

lapply(1:length(mat_lag),function(index)
  mapply(function(x, y) x*y,  t(Phi1), mat_lag[[index]]))
# Generalise(this may give something different)
#lapply(1:length(mat_lag),function(index)
#mapply(function(x, y) x*y,  t(PHI[[index]]), mat_lag[[index]]))

结果:

[[1]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    3   44  133    6   55  152    9   66  171
[2,]    4   48  140    8   60  160   12   72  180
[3,]    5   52  147   10   65  168   15   78  189
[4,]    6   56  154   12   70  176   18   84  198
[5,]    7   60  161   14   75  184   21   90  207

[[2]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    2   40  126    4   50  144    6   60  162
[2,]    3   44  133    6   55  152    9   66  171
[3,]    4   48  140    8   60  160   12   72  180
[4,]    5   52  147   10   65  168   15   78  189
[5,]    6   56  154   12   70  176   18   84  198

[[3]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    1   36  119    2   45  136    3   54  153
[2,]    2   40  126    4   50  144    6   60  162
[3,]    3   44  133    6   55  152    9   66  171
[4,]    4   48  140    8   60  160   12   72  180
[5,]    5   52  147   10   65  168   15   78  189

OP的示例结果:

mapply(function(x, y) x*y,  t(Phi1), mat_lag[[1]])
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    3   44  133    6   55  152    9   66  171
[2,]    4   48  140    8   60  160   12   72  180
[3,]    5   52  147   10   65  168   15   78  189
[4,]    6   56  154   12   70  176   18   84  198
[5,]    7   60  161   14   75  184   21   90  207
© www.soinside.com 2019 - 2024. All rights reserved.