Learn R Programming

Deducer (version 0.7-9)

sort.data.frame: Sort Data

Description

Sorts a data frame

Usage

"sort"(x, decreasing, by, ...)

Arguments

x
A data.frame to be sorted
decreasing
unused
by
A character, a one sided formula, or an expression indicating the sorting order
...
further arguments

Value

returns x, sorted.

Details

If by is a formula, or a character vector coerce-able into a formula, x is sorted by each element of the formula, with ties broken by subsequent elements. Elements preceded by a '-' indicate descending order, otherwise ascending order is used. Parentheses or any formula operator other than + and - are ignored, so sorting by a*b will sort based on the product of a and b. If by is not a formula, a ~ is appended to the left hand side of the call, and coerced into a formula. The decreasing argument is included for generic method consistency, and is not used.

See Also

sort order

Examples

Run this code
data(mtcars)

#sort by the number of cylenders
sort(mtcars, by= ~cyl)
sort(mtcars, by= cyl) #identical: no need for ~

#sort in descending order
sort(mtcars, by= -cyl)

#break ties with horse power
sort(mtcars,by= cyl +hp )
sort(mtcars,by= cyl -hp )

#randomly permute the data
sort(mtcars,by= rnorm(nrow(mtcars)) )

#reverse order
sort(mtcars,by= nrow(mtcars):1 )

#sort by squared deviation from mean hp
sort(mtcars,by= -(hp-mean(hp))^2 )
sort(mtcars,by= "-(hp-mean(hp))^2" ) #identical

Run the code above in your browser using DataLab