sort_by: Sort with auxiliary function

Description Usage Arguments Details Value See Also Examples

View source: R/sort_by.R

Description

Sort a vector or a list, given one or more auxiliary functions.

Usage

1
sort_by(x, ..., method = c("auto", "shell", "radix"))

Arguments

x

vector or list to sort.

...

one or several functions to apply to x. Use descending for reversed order.

method

the method for ties (see order).

Details

The output of the first function will be used as first key for sorting, the output of the second function as second key, and so on... Therefore, these outputs should be sortable (i.e. atomic vectors).

sort_by is inspired by sortBy in Haskell.

Value

A vector or list containing rearranged elements of x.

See Also

order which is used for rearranging elements.

Examples

1
2
3
4
sort_by(-3:2, abs)
sort_by(-3:2, abs, function(x) -x)
sort_by(list(5:7, 0, 1:4), length)
sort_by(list(1:2, 3:4, 5), length, descending(sum))

Example output

[1]  0 -1  1 -2  2 -3
[1]  0  1 -1  2 -2 -3
[[1]]
[1] 0

[[2]]
[1] 5 6 7

[[3]]
[1] 1 2 3 4

[[1]]
[1] 5

[[2]]
[1] 3 4

[[3]]
[1] 1 2

funprog documentation built on Jan. 13, 2021, 11:52 a.m.