Hadamard 乘积只是入口乘法,即 R 中的 *,但要从下面显示的列表 X 中获得 2x2 矩阵/列表,我们可以尝试以下任何方法。
1) 使用基础 R,我们有以下单行:
X <- list(R1 = 1:3, R2 = 4:6) # test data
m <- matrix(sapply(X, function(x) lapply(X, `*`, x)), 2)
给出这个 2x2 矩阵,我们可以使用m[[i, j]] 提取m 的第 i,j 个元素。
m
## [,1] [,2]
## [1,] Integer,3 Integer,3
## [2,] Integer,3 Integer,3
str(m)
## List of 4
## $ : int [1:3] 1 4 9
## $ : int [1:3] 4 10 18
## $ : int [1:3] 4 10 18
## $ : int [1:3] 16 25 36
## - attr(*, "dim")= int [1:2] 2 2
m[[1,2]]
## [1] 4 10 18
2) 甚至更简单但更乏味:
with(X, matrix(list(R1 * R1, R1 * R2, R2 * R1, R2 * R2), 2))
3) 另一种方法是使用outer 生成字符表达式矩阵m.ch,然后对其进行解析和评估。
m.ch <- outer(names(X), names(X), paste, sep = "*")
array(lapply(parse(text = m.ch), eval, X), dim(m.ch))
矩阵作为输出
虽然问题明确指出它需要一个列表作为答案,如果您也对矩阵感兴趣作为输出,这样它的块是 m 的条目,那么我们可以在预安装 Matrix 包的地方使用以下内容使用 R,因此不必安装。
library(Matrix)
Xmat <- do.call("rbind", X)
matrix(t(KhatriRao(Xmat)), 2, byrow = TRUE)
## [,1] [,2] [,3] [,4] [,5] [,6]
## [1,] 1 4 9 4 10 18
## [2,] 4 10 18 16 25 36
或从 (1) 中的 m 导出此矩阵:
matrix(unlist(m), 2, byrow = TRUE)