Eve Chanatasig
Eve Chanatasig

Reputation: 397

How to operate matrices within lists?

I am a new R user and now I am using the mapply command for operations between matrices; My original problem has two lists with 30 matrices each one; however, for explaining better my problem I will only use 6 matrices.

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)

My idea is to multiply the elements of PHI(i) with mat_lag[[i]].

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

The problem is that in my original problem I have 30 matrices and I do not want to do manually, extracting each element of the list. With the command above I get my desired result which is the following:

     [,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

However, I do not understand how to apply this command to the list such that my final result will be a list with 30 matrices size 5 * 9

Upvotes: 1

Views: 50

Answers (1)

NelsonGon
NelsonGon

Reputation: 13319

Not the most elegant(it may be slow for 30 matrices):

  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,]   20  130  288   22  140  306   24  150  324
[2,]   30  143  304   33  154  323   36  165  342
[3,]   40  156  320   44  168  340   48  180  360
[4,]   50  169  336   55  182  357   60  195  378
[5,]   60  182  352   66  196  374   72  210  396

[[3]]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,]    0  -27 -102   -1  -36 -119   -2  -45 -136
[2,]    0  -30 -108   -2  -40 -126   -4  -50 -144
[3,]    0  -33 -114   -3  -44 -133   -6  -55 -152
[4,]    0  -36 -120   -4  -48 -140   -8  -60 -160
[5,]    0  -39 -126   -5  -52 -147  -10  -65 -168

Result of OP's example:

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

Upvotes: 2

Related Questions