Learn R Programming

lsr (version 1.0.0)

sortFrame: Sort a data frame

Description

Sorts a data frame by one or more of its variables.

Usage

sortFrame(x, ..., alphabetical = TRUE)

Value

The sorted data frame.

Arguments

x

A data frame to be sorted.

...

One or more unquoted variable names to sort by, in order of priority. Prefix a variable name with - to sort in descending order (e.g., sortFrame(x, -a, b) sorts descending by a, then ascending by b).

alphabetical

Set to TRUE (the default) to sort character variables case-insensitively in alphabetical order. Set to FALSE to use the locale-dependent ordering used by sort.

Details

Sorts the rows of x by the variables listed in .... Numeric variables and factors are sorted by their numeric values (for factors, this corresponds to level order). Character variables are sorted alphabetically by default, ignoring case; prefix with - for reverse alphabetical order.

Simple expressions combining variables are also accepted (e.g., sortFrame(x, a + b) sorts by the sum of a and b), though care is required: the sort uses xtfrm internally to convert variables to sortable numeric codes, which can produce unexpected results for character variables when expressions other than - are used.

See Also

Examples

Run this code
dataset <- data.frame(
  txt = c("bob", "Clare", "clare", "bob", "eve", "eve"),
  num1 = c(3, 1, 2, 0, 0, 2),
  num2 = c(1, 1, 3, 0, 3, 2),
  stringsAsFactors = FALSE
)

sortFrame(dataset, num1) # sort by num1 ascending
sortFrame(dataset, num1, num2) # sort by num1 then num2
sortFrame(dataset, -num1) # sort by num1 descending
sortFrame(dataset, txt) # sort alphabetically (case-insensitive)

Run the code above in your browser using DataLab