【问题标题】:Apply an operation across multiple lists跨多个列表应用操作
【发布时间】:2017-07-20 17:02:01
【问题描述】:

我知道在 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]]
}

【问题讨论】:

    标签: r list matrix


    【解决方案1】:

    ReduceMap 的这种组合将在基础 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 2016-02-23
      • 1970-01-01
      • 2011-05-26
      相关资源
      最近更新 更多