Reputation: 7895
I have a matrix M and a matrix L that contains 'pair of rows indexes' that i need to select in M, in order to apply a function. The function returns a matrix with 2 rows and the same number of columns of 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)
The function f is:
f = function(r1, r2)
{
matrix(c(r1+r2, r1-r2), nrow = 2, byrow = T)
}
The thing is that a need to loop over L, apply f for each 'pair' and append the results to another matrix. So, for the code above the final result would be:
#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)
How can i vectorize this operation? The rows indexes in L are random, and the row order of the final result didn't matter.
Thanks for any help!
Upvotes: 0
Views: 1230
Reputation: 43255
What if you wrap your f
function in something that takes the matrix M
as an additional argument:
fm <- function(rowVector, mat) {
f(mat[rowVector[1],], mat[rowVector[2],])
}
then call it with 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
Upvotes: 2