sort_matrix: Sort matrix

View source: R/utils.R

sort_matrixR Documentation

Sort matrix

Description

Sort a matrix (or an object that can be coerced) by values in rows or columns.

Usage

sort_matrix(m, margin = 1L, order = NULL, na.last = TRUE, index.return = FALSE)

Arguments

m

a matrix, usually an integer matrix

margin

margin to sort by; default is to sort on row values (margin = 1); sort on column values using margin = 2

order

vector specifying all unique values of m in the desired order; if NULL, the order will be the sorted unique values of m

na.last

logical; if TRUE, missing values are put last; if FALSE, they are put first; see order

index.return

logical; if TRUE, ordering indices are returned

Examples

set.seed(1)
m <- +!!matrix(rpois(5 * 10, 1), 5)

## sort columns by decreasing row values
sort_matrix(m)

## return ordering vector
o <- sort_matrix(m, index.return = TRUE)
stopifnot(
  identical(sort_matrix(m), m[, o])
)

## sort rows by decreasing column values
sort_matrix(m, 2)

## sort first by column then by row
sort_matrix(m, 2:1)
## equivalent to
sort_matrix(sort_matrix(m, 2), 1)

## compare: default vs sort 0s first followed by 4,3,2,1
set.seed(1)
m <- matrix(rpois(5 * 10, 1), 5)
sort_matrix(m, 2)
sort_matrix(m, order = c(0, 4:1))


raredd/rawr documentation built on March 4, 2024, 1:36 a.m.