gpt4 book ai didi

r - 跨多个列表应用操作

转载 作者:行者123 更新时间:2023-12-04 10:37:34 24 4
gpt4 key购买 nike

我知道在 R 中,如果我有一个矩阵列表,我可以使用 Reduce 函数对所有矩阵应用操作。例如:

l <- list(matrix(rnorm(16), 4, 4), matrix(rnorm(16), 4, 4))
Reduce(`*`, l)

但是如果我想跨多个列表应用此操作怎么办?我可以使用 for 循环进行暴力破解,但我觉得应该有更好的方法。我可以使用 mapply

做两个列表
l2 <- l
mapply(`*`, l, l2, SIMPLIFY = FALSE)

但如果我有两个以上,我不确定如何解决。

以下想法都会导致错误:

l3 <- l2
mapply(`*`, l, l2, l3, SIMPLIFY = FALSE)
Error in .Primitive("*")(dots[[1L]][[1L]], dots[[2L]][[1L]], dots[[3L]][[1L]]) :
operator needs one or two arguments

Reduce(`*`, list(l, l2, l3))
Error in f(init, x[[i]]) : non-numeric argument to binary operator

所需的输出是一个长度为 2 的列表,其中包含每个列表中每个矩阵的元素乘积。暴力循环看起来像这样:

out <- vector("list", length = 2)
for(i in 1:2){
out[[i]] <- l[[i]] * l2[[i]] * l3[[i]]
}

最佳答案

这种 ReduceMap 的组合将在 base R 中产生所需的结果。

# copy the matrix list
l3 <- l2 <- l

out2 <- Reduce(function(x, y) Map(`*`, x, y), list(l, l2, l3))

返回

out2
[[1]]
[,1] [,2] [,3] [,4]
[1,] -5.614351e-01 -0.06809906 -0.16847839 0.8450600
[2,] -1.201886e-05 0.02008037 5.64656727 -2.4845526
[3,] 5.587296e-02 -0.54793853 0.02254552 0.4608697
[4,] -9.732049e-04 11.73020448 1.83408770 -1.4844601

[[2]]
[,1] [,2] [,3] [,4]
[1,] -4.7372339865 -0.398501528 0.8918474 0.12433983
[2,] 0.0007413892 0.151864126 -0.2138688 -0.10223482
[3,] -0.0790846342 -0.413330364 2.0640126 -0.01549591
[4,] -0.1888032661 -0.003773035 -0.9246891 -2.30731237

我们可以检查这是否与 OP 中的 for 循环相同。

identical(out, out2)
[1] TRUE

关于r - 跨多个列表应用操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45220975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com