使用 map2 将 R 中的两个以上矩阵列表相乘

use map2 to multiply more than two lists of matrices in R

我有

A = list(a = matrix(1:4, 2), b = matrix(2:5, 2))

G = list(a = matrix(10:13, 2), b = matrix(25:28, 2))

columns <- list(a = matrix(3:4, 1), b = matrix(1:2, 1))

我想制作另一个跨列表的所有同名元素的叉积列表,所以我做了 purrr::map2(A, G, columns, `%*%`)。看起来 map2 不允许超过两个元素。有解决方法吗?

Error in `stop_bad_length()`:
! Index 1 must have length 1, not 2
Backtrace:
 1. purrr::map2(A, G, columns, `%*%`)
 4. purrr:::stop_bad_element_length(...)
 5. purrr:::stop_bad_length(...)

我也试过purrr::pmap(list(A, G, columns), %*%),但没有成功。

purrr::map2(A, G, `%*%`) 效果很好。

问题是您尝试应用的函数 ('%*%') 是一个只接受两个参数而不是三个参数的函数。

对于您的问题,我建议使用 Reduce(或 purrr::reduce):在这种情况下,Reduce 从两个矩阵开始并将它们相乘。然后它将结果与第三个矩阵相乘。理论上你可以这样下去。

lapply(seq_along(A), \(k) Reduce('%*%', list(A[[k]],G[[k]], t(columns[[k]]))))

[[1]]
     [,1]
[1,]  333
[2,]  496

[[2]]
     [,1]
[1,]  486
[2,]  647

请注意,我必须转置 column 内的矩阵,因为它们的大小不正确。

类似于@Cettt 在 tidyverse 中的方法 - 我们在 pmap 中接受 list,然后 reduce%*%。请注意,'columns' 元素需要 transposed

library(purrr)
pmap(list(A, G, columns), ~ reduce(list(..1, ..2, t(..3)), `%*%`))
$a
     [,1]
[1,]  333
[2,]  496

$b
     [,1]
[1,]  486
[2,]  647

或者 Map 来自 base R

的选项
Map(\(x, y, z) Reduce(`%*%`, list(x, y, t(z))), A, G, columns)
$a
     [,1]
[1,]  333
[2,]  496

$b
     [,1]
[1,]  486
[2,]  647