sorting - How to sort a matrix/data.frame by all columns in R -
sorting - How to sort a matrix/data.frame by all columns in R -
i have matrix, e.g.
a = rep(0:1, each=4) b = rep(rep(0:1, each=2), 2) c = rep(0:1, times=4) mat = cbind(c,b,a)
i need sort columns of matrix. know how sorting specific columns (i.e. limited number of columns).
mat[order(mat[,"c"],mat[,"b"],mat[,"a"]),] c b [1,] 0 0 0 [2,] 0 0 1 [3,] 0 1 0 [4,] 0 1 1 [5,] 1 0 0 [6,] 1 0 1 [7,] 1 1 0 [8,] 1 1 1
however, need generic way of doing without calling column names, because have number of columns. how can sort big number of columns?
here's concise solution:
mat[do.call(order,as.data.frame(mat)),]; ## c b ## [1,] 0 0 0 ## [2,] 0 0 1 ## [3,] 0 1 0 ## [4,] 0 1 1 ## [5,] 1 0 0 ## [6,] 1 0 1 ## [7,] 1 1 0 ## [8,] 1 1 1
the phone call as.data.frame()
converts matrix data.frame in intuitive way, i.e. each matrix column becomes list component in new data.frame. that, can pass each matrix column single invocation of order()
passing listified form of matrix sec argument of do.call()
.
this work number of columns.
it's not dumb question. reason mat[order(as.data.frame(mat)),]
not work because order()
not order data.frames row. instead of returning row order data.frame based on ordering column vectors left right (which solution does), flattens data.frame single big vector , orders that. so, in fact, order(as.data.frame(mat))
equivalent order(mat)
, matrix treated flat vector well. particular data, returns 24 indexes, theoretically used index (as vector) original matrix mat
, since in look mat[order(as.data.frame(mat)),]
you're trying utilize them index row dimension of mat
, of indexes past highest row index, "subscript out of bounds" error.
see ?do.call
. don't think can explain improve help page; take @ examples, play them until how works. basically, need phone call when arguments want pass single invocation of function trapped within list. can't pass list (because you're not passing intended arguments, you're passing list containing intended arguments), there must primitive function "unwraps" arguments list function call. mutual primitive in programming languages functions first-class objects, notably (besides r's do.call()
) javascript's apply()
, python's (deprecated) apply()
, , vim's call()
.
r sorting matrix order
Comments
Post a Comment