sort_by {base} | R Documentation |
Sorting Vectors or Data Frames by Other Vectors
Description
Generic function to sort an object in the order determined by one or more other objects, typically vectors. A method is defined for data frames to sort its rows (typically by one or more columns), and the default method handles vector-like objects.
Usage
sort_by(x, y, ...)
## Default S3 method:
sort_by(x, y, ...)
## S3 method for class 'data.frame'
sort_by(x, y, ...)
Arguments
x |
An object to be sorted, typically a vector or data frame. |
y |
Variables to sort by. For the default method, this can be a vector, or more generally any
object that has a For the |
... |
Additional arguments, typically passed on to
|
Value
A sorted version of x
. If x
is a data frame, this means
that the rows of x
have been reordered to sort the variables
specified in y
.
See Also
Examples
mtcars$am
mtcars$mpg
with(mtcars, sort_by(mpg, am)) # group mpg by am
## data.frame method
sort_by(mtcars, runif(nrow(mtcars))) # random row permutation
sort_by(mtcars, list(mtcars$am, mtcars$mpg))
# formula interface
sort_by(mtcars, ~ am + mpg) |> subset(select = c(am, mpg))
sort_by.data.frame(mtcars, ~ list(am, -mpg)) |> subset(select = c(am, mpg))