【问题标题】:R apply function to selected pairs or rowsR将函数应用于选定的对或行
【发布时间】:2012-09-14 20:13:51
【问题描述】:

我有一个矩阵 M 和一个矩阵 L,其中包含我需要在 M 中选择的“行索引对”,以便应用函数。函数返回一个2行列数相同的矩阵M:

set.seed(1)
# M has even number of rows
M = matrix(runif(24), ncol = 3)
# each row of L is a pair of row indexes that will be selected in M
# so the first 'pair' is M[1,] M[3,], the second is M[2,] M[4,] and so on
L = matrix(c(1,3,2,4,6,7), ncol = 2, byrow = T)

函数f是:

f = function(r1, r2)
{
 matrix(c(r1+r2, r1-r2), nrow = 2, byrow = T)
}

问题是需要循环 L,为每个“对”应用 f 并将结果附加到另一个矩阵。因此,对于上面的代码,最终结果将是:

#first row of L
res1 = f(M[1,], M[3,])
#second row of L
res2 = f(M[2,], M[4,])
#third row of L
res3 = f(M[6,], M[7,])

#append everything
RES = rbind(res1, res2, res3)

如何向量化这个操作? L 中的行索引是随机的,与最终结果的行顺序无关。

感谢您的帮助!

【问题讨论】:

    标签: r matrix vectorization


    【解决方案1】:

    如果您将 f 函数包装在将矩阵 M 作为附加参数的东西中:

    fm <- function(rowVector, mat) {
      f(mat[rowVector[1],], mat[rowVector[2],])
    }
    

    然后用apply调用它:

    apply(L, 1, fm, mat=M)
    
               [,1]       [,2]        [,3]
    [1,]  0.8383620  1.2803317  1.84306495
    [2,] -0.3073447 -0.5360839 -0.04628558
    [3,]  0.8350886  0.2383430  1.15394514
    [4,]  0.4231395 -0.1147705 -0.38573770
    [5,]  1.0976537  1.7693513  0.86381629
    [6,]  0.3375833  0.2144609 -0.43953124
    

    【讨论】:

    • 您的解决方案看起来不错,但我得到了不同的结果!顺便说一句,最终结果的行顺序无关紧要。
    • 我只是添加了 matrix(t(apply(L,1,fm,mat = M)), byrow = F, ncol = 3),我认为它可以解决问题!
    猜你喜欢
    • 2021-09-14
    • 2016-08-11
    • 2022-11-08
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 2011-07-11
    • 1970-01-01
    相关资源
    最近更新 更多