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