繁体   English   中英

如何在嵌套列表中操作矩阵?

[英]How to operate matrices within nested lists?

我是使用嵌套列表的新手。 因此,假设我的数据具有以下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在我的代码中定义索引。

有多种方法可以实现您的目标。 (我假设您想要矩阵乘法%*%而不是逐项乘法* 。这里我将使用 tcrossprod)
这里有2个选项

多个 for 循环

result1 <- vector('list', 3)
for(i in 1:3){
  result1[[i]] <- vector('list', 3)
  for(j in 1:2){
    result1[[i]][[j]] <- tcrossprod(PHI[[j]][[i]], mat_lag[[i]])
  }
}

嵌套 lapply 函数(循环隐藏)

result2 <- lapply(1:3, function(x)lapply(1:2, function(z){
  tcrossprod(PHI[[z]][[x]], mat_lag[[x]])
}))

两者都使用索引来迭代列表。
我们几乎可以使用mapply复制它

result3 <- lapply(1:2, function(x)mapply(function(x, y) tcrossprod(x, y), x = PHI[[x]], y = mat_lag))

但这会将结果返回为一个大矩阵 output (并转置结果),因此必须进行一些进一步的格式化。

Product <- lapply(1:length(PHI), function(index)
  lapply(1:length(mat_lag), function(z)
    mapply(function(x, y) x*y, t(PHI[[index]][[z]]), mat_lag[[index]])
    ))

暂无
暂无

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

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