|
Sorting Data
There will be times when sorting data based on variable values will be needed. This can be accomplished via the order function. A few examples are provided in the following sections. Sorting data based on single variable
Sorting data based on the values of a variable (column) can be achieved via the with and order functions. This method sorts by ascending value by default. To sort by descending value, add a decreasing = TRUE argument in the order function. Ascending: SortedData = UnsortedObjectName [ with(UnsortedObjectName, order( SortVariable)) , ] or Descending: SortedData = UnsortedObjectName [ with(UnsortedObjectName, order( SortVariable, decreasing = TRUE)) , ] EXAMPLE: > library(boot) > SortedData = channing [ with(channing, order (sex)), ] or > library(boot) > SortedData = channing [ with(channing, order (sex, decreasing = TRUE)), ] Sorting data based on multiple variables
Sorting data based on the values of multiple variables (columns) can be achieved via the order function. The function sorts by ascending value by default. To sort by descending value, add a minus sign (-) before the sort variable name. You can add as many sort variables as desired separated by column. The function will first sort by the first sort variable, then the second, etc. Ascending: SortedData = UnsortedObjectName [ with(UnsortedObjectName, order( SortVariable1, SortVariable2, etc)) , ] or Descending: SortedData = UnsortedObjectName [ with(UnsortedObjectName, order( SortVariable1, SortVariable2, etc, decreasing = TRUE)) , ] EXAMPLE: > library(boot) > SortedData = channing [ with(channing, order (sex, entry)), ] or > library(boot) > SortedData = channing [ with(channing, order (sex, entry, decreasing = TRUE)), ] |