【发布时间】:2020-05-22 14:55:54
【问题描述】:
我是使用嵌套列表的新手。所以,假设我的数据有以下dput:
mat_lag <- list(structure(list(V1 = 3:7, V2 = 11:15, V3 = 19:23), row.names = c(NA,
-5L), class = "data.frame"), structure(list(V1 = 2:6, V2 = 10:14,
V3 = 18:22), row.names = c(NA, -5L), class = "data.frame"),
structure(list(V1 = 1:5, V2 = 9:13, V3 = 17:21), row.names = c(NA,
-5L), class = "data.frame"))
和
PHI <- list(list(structure(1:9, .Dim = c(3L, 3L)), structure(1:9, .Dim = c(3L,
3L)), structure(1:9, .Dim = c(3L, 3L))), list(structure(1:9, .Dim = c(3L,
3L)), structure(1:9, .Dim = c(3L, 3L)), structure(1:9, .Dim = c(3L,
3L))))
我的想法是将mat_lag 中的3 个矩阵与PHI 中嵌套列表内的3 个矩阵相乘。我的问题是我不确定如何操作嵌套列表,我只能为一个嵌套列表编写代码。
让我解释得更好。我正在寻找逐项乘法
如果我使用PHI[[1]],代码如下:
Product <- lapply(1:length(mat_lag), function(index)
mapply(function(x, y) x*y, t(PHI[[1]][[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
我想在PHI更改时重复这个操作,这意味着我想使用PHI[[1]]和PHI[[2]]。
我认为我可以使用for 循环或者function,但我使用function 在我的代码中定义索引。
【问题讨论】: