Vectorizing order in R -


i trying order each row in matrix few columns , many rows. there vectorized version of in r? more concretely, let's set our seed 10 , make example matrix:

set.seed(10) example.matrix = replicate(12,runif(500000)) 

to order example.matrix, would,

ordered.example = apply(example.matrix,1,order) 

but slow , love faster. analogy,

rowsums(example.matrix) 

is preferable to,

apply(example.matrix,1,sum) 

much appreciated.

here's way of speeding 10x. it's tailored example , depending on real data method may or may not work.

the idea add 0 first row, 1 second , on, collapse vector, sort , recombine matrix:

n = 12; m = 500000; d = replicate(n,runif(m))  system.time(d1<-t(apply(d, 1, order))) #   user  system elapsed  #  11.26    0.06   11.34   system.time(d2<-matrix(order(as.vector(t(matrix(as.vector(d) + 0:(m-1), nrow = m)))) -                        rep(0:(m-1), each = n)*n, nrow = m, byrow = t)) #   user  system elapsed  #   1.39    0.14    1.53   # note: reason identical() fails, 2 in fact same sum(abs(d1-d2)) # 0 

Comments

Popular posts from this blog

node.js - Bad Request - node js ajax post -

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -