r - Getting rows of a subcolumns of a matrix which coincide with a series of vectors, without using apply -


this bit of challenging 1 did best reproducible/follow guidelines/etc.

this related earlier question here, want add 1 more dimension. solution needs fast, no looping, apply, or slow merges if possible.

consider below:

set.seed(1)      m = matrix(rpois(50,5),5,5)            v1 = c(4  ,  8  ,  3 ,   5 ,   9)                v2 = c(5  ,  6  ,  6 ,  11  ,  6)         v3 = c( 5  ,  6 ,   6 ,  11  ,  6)         v4=  c(8, 6,  4, 4, 3)         v5 =  c(4  ,  8  ,  3 ,   5  ,  9)         v6=  c(8  ,  6  ,  4  ,  4 ,   3)         v7 = c( 3 ,   2  ,  7   , 7 ,   4)         v8=  c(3  ,  2   , 7   , 7  ,  4)  row1 = c(v1,v2) row2 = c(v3,v4)  row3 = c(v5,v6)  row4 = c(v7,v8)  vmat = rbind(row1,row2,row3,row4)        m      [,1] [,2] [,3] [,4] [,5] [1,]    4    8    3    5    9 [2,]    4    9    3    6    3 [3,]    5    6    6   11    6 [4,]    8    6    4    4    3 [5,]    3    2    7    7    4      vmat      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] row1    4    8    3    5    9    5    6    6   11     6 row2    5    6    6   11    6    8    6    4    4     3 row3    4    8    3    5    9    8    6    4    4     3 row4    3    2    7    7    4    3    2    7    7     4 

each row of vmat composed of 2 rows of m stacked side side. hence...

consider mentally vmat 2 matrices (in problem, many more 2, 500,000 across) between columns 5 , 6.

for each submatrix of vmat, want each row vector corresponds row in m.

the output should be...          [,1] [,2] [1,]    1    3 [2,]    3    4 [3,]    1    4 [4,]    5    5 

i'm thinking maybe stacking vmat matrix in this question first pass, doing row lookups, reshaping.

one possible solution ...

getmatchingvec <- function(vmat, m){    # function generate sub matrixs     getvmatsubset <- function(vmat, m){     lapply(1:(ncol(vmat)/ncol(m)),             fun = function(x, y = ncol(m), mat = vmat){              <- (x - 1) * y + 1              j <- (x - 1) * y + y              subset(mat, select = i:j)            })    }    # lapply on sub`s, apply each ros     resultlist <-      lapply(getvmatsubset(vmat, m),              fun = function(svmat, matm = m)                   apply(svmat, 1, fun = function(x, mat = matm)                    which(colsums(t(m) == x) == ncol(m))))    do.call(cbind, resultlist) }   # function call getmatchingvec(vmat, m) 

Comments