sort_by: sort_by the Rows of a Data Frame

View source: R/sort_by.R

sort_byR Documentation

sort_by the Rows of a Data Frame

Description

Sorts the values of a data frame according to the values of one or more variables contained in the data frame, or the row names. Variable types include numeric and factor variables. Factors are sorted by the ordering of their values, which, by default is alphabetical. Sorting by row names is also possible.

Usage

sort_by(data=d, by, direction=NULL, quiet=getOption("quiet"), ...)

Sort(...)

Arguments

data

The name of the data frame from which to create the subset, which is d by default.

by

One or more variables to be sorted, or just the character string row.names or random.

direction

Default is ascending for all variables listed in by. Or, specify a list of "+" for ascending and "-" for descending, one for each variable to be sorted.

quiet

If set to TRUE, no text output. Can change system default with style function.

...

Other parameter values.

Details

sort_by sorts the rows of a data frame and lists the first five rows of the sorted data frame. Specify the values upon which to base the sort with the required by parameter. If not all sorted variables are sorted in ascending order, then also specify a sequence of "+" for ascending and "-" for descending, respectively, one for each variable to be sorted. If row.names or random is specified, then no other variables can be specified.

A list of consecutive variables can be specified using the colon notation, such as Years:Salary To specify a list of multiple variables, or "+" and "-" signs, or sets of variables, separate each set of variables or each sign by a comma, then invoke the R combine or c function. For example, if three variables are to be sorted, the first two ascending and the last descending, then specify, direction=c("+","+","-").

sort_by is based on the standard R function order, though the sort_by function allows for the sorting of factors, whereas order does not.

Value

The sorted data frame is returned, usually assigned the name of d as in the examples below. This is the default name for the data frame input into the lessR data analysis functions.

Author(s)

David W. Gerbing (Portland State University; gerbing@pdx.edu)

See Also

order.

Examples

# construct data frame
d <- read.table(text="Severity Description
1 Mild
4 Moderate
3 Moderate
2 Mild
1 Severe", header=TRUE)

# sort the data frame called d according to Severity
#   in ascending order
d <- sort_by(d, Severity)

# sort Description in descending order, sort Severity within
#  each level of Description in ascending order
d <- sort_by(d, c(Description, Severity), direction=c("-", "+"))  

# sort by row names in ascending order
d <- sort_by(d, row.names)

# randomly re-shuffle the rows of data
d <- sort_by(d, random)

lessR documentation built on Nov. 12, 2023, 1:08 a.m.