【问题标题】:How to multiply vectors of different sized lists in R如何在R中乘以不同大小列表的向量
【发布时间】:2019-08-23 17:34:10
【问题描述】:

我正在尝试将列表中包含的向量乘以另一个列表中的另一个向量。

每个列表的元素大小不同。

要相乘的列表是Concat_listList_3

set.seed(10)
List_1 <- rep(list(matrix(runif(10), nrow = 10, ncol = 1)), 2)
List_2 <- rep(list(matrix(runif(10), nrow = 10, ncol = 1)), 2)
Concat_list <- lapply(seq(List_1), function(i) {
  matrix(mapply(c, List_1[[i]], List_2[[i]], SIMPLIFY = F) )  })
List_3 <- list(c(50, 25), c(10, 18))

如何将Concat_list 的每个元素的每一行乘以List_3 的相应向量?

即:

Concat_list[[1]][[1]] * List_3[[1]]
Concat_list[[1]][[2]] * List_3[[1]]
Concat_list[[1]][[3]] * List_3[[1]]
# ...etc
Concat_list[[2]][[1]] * List_3[[2]]
Concat_list[[2]][[2]] * List_3[[2]]
# ...etc

我试过了:

lapply(seq(Concat_list), function(i){
  lapply(Concat_list[[i]], function(x){
  x[[i]] * List_3[[i]]
  }) 
})

lapply(seq(Concat_list), function(i){
  sapply(Concat_list[[i]], function(x){
    x[[i]] * List_3[[i]]
  })
})

Test <- lapply(seq(Concat_list), function(i) {
  matrix(mapply(function(x, y){x*y}, Concat_list[[i]], List_3[[i]], SIMPLIFY = F) )  })

Test_2 <- rep(list(matrix(nrow = nrow(Concat_list[[1]]), ncol = 1)) , length(Concat_list) )
for(i in seq(Concat_list)){
  for(j in seq(Concat_list[[i]])){
    Test_2[[i]][j] <- unlist(Concat_list[[i]][j]) * List_3[[i]]
  }
}

Map('*', Concat_list[[1]], List_3[[1]])

这些都不是很有效,我试图避免双 for 循环。

我还尝试将unlist() 放在不同的地方,但没有成功。

这是 Concat_list 的第一个元素在 for 循环中的预期输出:

# Correct for(i in 1:10){print(unlist(Concat_list[[1]][i]) * List_3[[1]])}

同样的事情,但更明确地说明。

c(0.5074782, 0.6516557) * List_3[[1]]
c(0.3067685, 0.5677378) * List_3[[1]]
c(0.4269077, 0.1135090) * List_3[[1]]

谢谢

【问题讨论】:

  • 正如@mt1022 所建议的那样 - 在计算之前将该列表转换为矩阵可能是一个好主意,例如。通过:t(matrix(unlist(Concat_list), nrow = 2));否则@mt1022 的好答案

标签: r list loops vector apply


【解决方案1】:

这是你想要的吗:

res <- Map(
    function(x, y){ as.matrix(lapply(x, function(i){ i * y })) },
    Concat_list, List_3)

这是最终结果的一部分:

> res[[1]][[1]]
[1] 25.37391 16.29139
> res[[1]][[2]]
[1] 15.33843 14.19344
> res[[2]][[1]]
[1]  5.074782 11.729802
> res[[2]][[2]]
[1]  3.067685 10.219280

在我看来,您的Concat_list 太复杂了。也许您可以将其简化为 10x2 矩阵的列表。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    相关资源
    最近更新 更多