【问题标题】:Using mapply to perform operations on lists of vectors: trouble with index specification使用 mapply 对向量列表执行操作:索引规范的问题
【发布时间】:2016-06-09 00:16:39
【问题描述】:

我有两个列表(A 和 B),每个列表包含 5 个长度为 3 的向量。我还有一个 3x3 矩阵 Z。

我想使用 B 和 Z 对 A 的元素执行操作,并将其输出到 3x5 矩阵。我可以使用如下的for循环成功地做到这一点

#Create two lists of vectors
A = list(c(1,2,1), c(2,1,2), c(3,2,2),c(1,2,5),c(1,4,2))
B = list(c(2,3,1), c(1,3,4), c(2,5,2), c(2,4,1),c(1,4,1))
#Create 3x3 matrix
Z = rbind(c(2,3,5),c(3,2,3), c(1,1,1))

#initialize empty 3x5 matrix
Y = matrix(NA,3,5)

for (i in 1:3)
{
  for (j in 1:5)
  {
    #Take the ith element of the jth vector from A, and divide it by
    #the dot product of the jth vector from B and the ith row of Z
    Y[i,j] = A[[j]][i] / sum(B[[j]]*Z[i,])
  }
}

这会返回(对于 Y)

           [,1]       [,2]       [,3]       [,4]       [,5]
[1,] 0.05555556 0.06451613 0.10344828 0.04761905 0.05263158
[2,] 0.13333333 0.04761905 0.09090909 0.11764706 0.28571429
[3,] 0.16666667 0.25000000 0.22222222 0.71428571 0.33333333

我正在尝试弄清楚如何使用 mapply 来提高效率。

到目前为止,我得到了这个:

mapply(function(x,y,z) x/sum(y*z), x=A,y=B,z = Z)

但这不能正常工作。我认为也许将任务分成两个单独的 mapply 可能会奏效,也许我需要重新组织矩阵和列表,以便索引以某种方式匹配。我在 apply 系列函数方面取得了一些成功,但我还不够流利,无法弄清楚如何最好地解决这个问题。如有任何指导,我将不胜感激。

【问题讨论】:

    标签: r list vector mapply


    【解决方案1】:

    我决定把它分成两个步骤,就像你想的那样。这是一种方法:

    BZ <- lapply(B, FUN = function(y) 
        apply(Z, 1, FUN = function(x) sum(y*x)))
    
    mapply(function(x,y) x / y, x = A, y = BZ)
    
               [,1]       [,2]       [,3]       [,4]       [,5]
    [1,] 0.05555556 0.06451613 0.10344828 0.04761905 0.05263158
    [2,] 0.13333333 0.04761905 0.09090909 0.11764706 0.28571429
    [3,] 0.16666667 0.25000000 0.22222222 0.71428571 0.33333333
    

    【讨论】:

    • 啊!太感谢了。您的回答不仅解决了我的问题,也将帮助我在申请家庭中变得更好。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多