r - Compare a vector with selected element from a matrix -


i want compare huge vector selected element matrix in r.

a matrix , b vector. want compare each element of b selected element a. c , d selection criteria. vectors of same length b. c specifies row number of a, , d specifies column number. of dimension 10*100, , b,c,d vectors of length 72000. code loop:

for ( j in 1:length(b) ){   e[j] <- b[j] >= a[ c[j], d[j] ] }  

this slow. vectorize define vector including elements first:

a1 <- array(0, length(b)) a2 <- a[,d] ( j in 1:length(b) ){   a1[j] <- a2[ c[j], j ] }    e <- b >= a1 

this still slow. there better way this?

the absolute fastest way can think of treat vector , extract elements want. matrix is vector dimension attributes. arithmetic operations extremely fast , [ subsetting operator vectorised.

to desired elements need multiply desired column number (d) total number of rows , subtract desired row number (c) minus total number of rows, eg a[ d * nrow(a) - ( nrow(a) - c) ] in example:

set.seed(1234) <- matrix( sample(5,16,repl=true) , 4 ) #    [,1] [,2] [,3] [,4] #[1,]    2    1    1    5 #[2,]    1    3    5    5 #[3,]    2    1    1    2 #[4,]    1    4    2    1  ## rows c <- sample( nrow(a) , 3 , repl = true ) #[1] 1 2 3  ## columns d <- sample( ncol(a) , 3 , repl = true ) #[1] 1 3 2  ## treat vector ## elements given by: rs <- nrow(a) a[ d * rs - ( rs - c) ] #[1] 2 5 1 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -