在R中将两个不同长度的列表相乘
Multiply two lists of different length in R
我有两个结构不同的列表。列表 A 是一个数据帧列表(包含 1 行和 10 列),列表 B 是一个矩阵 10x 10 的列表,如下所示:
List A
[[1]]
[1] dataframe (of 1 column)
[[2]]
[1] dataframe (of 1 column)
List B
[[1]]
[1] num (1:10)
[[2]]
[2] num (10 x 10)
Example:
ListA <- list(A = A <- data.frame(matrix(rnorm(10), ncol = 10, nrow = 1)),
B = B <- data.frame(matrix(rnorm(10), ncol = 10, nrow = 1)))
ListB <- list(B = A <- rnorm(10),
A = B <- rnorm(10)
C = C <- rnorm(10) )
我想为列表 B 的每个向量乘以 (%*%
) lits A 的每个数据帧。
像这样:A%*%B, A%*%A, A%*%C, B%*%B, B%*%A, B%*%C
并且还有计算每个元素名称的结果。
我尝试了 Map(%*%, ListA, ListB)
但没有用。
尝试lapply
解决方案:
lapply(1:length(ListA), function(x) lapply(1:length(ListB),
function(y) as.matrix(ListA[[x]]) %*% ListB[[y]]))
[[1]]
[[1]][[1]]
[,1]
[1,] -4.061742
[[1]][[2]]
[,1]
[1,] -1.401807
[[1]][[3]]
[,1]
[1,] -1.53459
[[2]]
[[2]][[1]]
[,1]
[1,] 3.439579
[[2]][[2]]
[,1]
[1,] 2.44288
[[2]][[3]]
[,1]
[1,] 3.475746
我们也可以通过遍历对象来做到这一点
lapply(ListA, function(x) lapply(ListB, function(y) as.matrix(x) %*% y))
我想你可以像下面那样尝试 outer
outer(ListA,ListB,FUN = Vectorize(function(x,y) as.matrix(x)%*%y))
结果看起来像
B A C
A -1.336335 -1.291103 0.0925648
B -3.270517 4.648139 -3.8720215
我有两个结构不同的列表。列表 A 是一个数据帧列表(包含 1 行和 10 列),列表 B 是一个矩阵 10x 10 的列表,如下所示:
List A
[[1]]
[1] dataframe (of 1 column)
[[2]]
[1] dataframe (of 1 column)
List B
[[1]]
[1] num (1:10)
[[2]]
[2] num (10 x 10)
Example:
ListA <- list(A = A <- data.frame(matrix(rnorm(10), ncol = 10, nrow = 1)),
B = B <- data.frame(matrix(rnorm(10), ncol = 10, nrow = 1)))
ListB <- list(B = A <- rnorm(10),
A = B <- rnorm(10)
C = C <- rnorm(10) )
我想为列表 B 的每个向量乘以 (%*%
) lits A 的每个数据帧。
像这样:A%*%B, A%*%A, A%*%C, B%*%B, B%*%A, B%*%C
并且还有计算每个元素名称的结果。
我尝试了 Map(%*%, ListA, ListB)
但没有用。
尝试lapply
解决方案:
lapply(1:length(ListA), function(x) lapply(1:length(ListB),
function(y) as.matrix(ListA[[x]]) %*% ListB[[y]]))
[[1]]
[[1]][[1]]
[,1]
[1,] -4.061742
[[1]][[2]]
[,1]
[1,] -1.401807
[[1]][[3]]
[,1]
[1,] -1.53459
[[2]]
[[2]][[1]]
[,1]
[1,] 3.439579
[[2]][[2]]
[,1]
[1,] 2.44288
[[2]][[3]]
[,1]
[1,] 3.475746
我们也可以通过遍历对象来做到这一点
lapply(ListA, function(x) lapply(ListB, function(y) as.matrix(x) %*% y))
我想你可以像下面那样尝试 outer
outer(ListA,ListB,FUN = Vectorize(function(x,y) as.matrix(x)%*%y))
结果看起来像
B A C
A -1.336335 -1.291103 0.0925648
B -3.270517 4.648139 -3.8720215