0

我有一个矩阵 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 中的行索引是随机的,最终结果的行顺序无关紧要。

谢谢你的帮助!

4

1 回答 1

2

如果您将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
于 2012-09-14T20:23:27.917 回答