r - Printing the sorted elements of a matrix in descending order with array indices in the fastest fashion -
this seems simple problem having trouble doing in fast manner.
say have matrix , want sort matrix , store indices of elements in descending order. there quick way this? right now, extracting maximum, storing result, changing -2, , extracting next maximum in loop. inefficient way it.
my problem requires me work on 20,000 x 20,000 matrix. memory not issue. ideas fastest way great.
for example if have matrix
>m<-matrix(c(1,4,2,3),2,2) >m [,1] [,2] [1,] 1 2 [2,] 4 3
i want result indicate numbers in descending order:
row col val 2 1 4 2 2 3 1 2 2 1 1 1
here's possible data.table
solution
library(data.table) rows <- nrow(m) ; cols <- ncol(m) res <- data.table( row = rep(seq_len(rows), cols), col = rep(seq_len(cols), each = rows), val = c(m) ) setorder(res, -val) res # row col val # 1: 2 1 4 # 2: 2 2 3 # 3: 1 2 2 # 4: 1 1 1
edit: base r alternative
res <- cbind( row = rep(seq_len(rows), cols), col = rep(seq_len(cols), each = rows), val = c(m) ) res[order(-res[, 3]),] # row col val # [1,] 2 1 4 # [2,] 2 2 3 # [3,] 1 2 2 # [4,] 1 1 1
Comments
Post a Comment