我有一个矩阵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中的行索引是随机的,最终结果的行顺序无关紧要。
感谢您的帮助!
答案 0 :(得分: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