Sorting Entries in a Data Frame by Column (order {base})Megan KressSeptember 28, 2016
extract FunctionThe order function sorts data in ascending order; however, sorting entries in a data frame is not as simple as calling the order function on the data frame. The function order reutrns a permentation, which rearranges the first argument. The first argument should be a vector, but if more than one vector is entered, the following vectors will be used as “tie-breakers.” For more information on the order function, see the CRAN page for the base package. For this example, I used a data set from the MASS package called ChickWeight.
Preparation
Order by Weight OnlyWe will now use the order function to sort the data set by the chicks’ weights.
Order by Weight Then TimeUsing the property of the function order that it takes multiple vector arguments, we will add a second sorting parameter (time).
We can see from the results that adding Time as a sorting parameter changed the ordering of the chicks. Chick #26 (first column name reference) moved from the second sorted row to the ninth sorted row because its time was 2 whereas all other chicks with weight 39 had times of 0.
Why Sort?Sorting data frames can be important if you are trying to run algorithms involving search or lookup or if you are trying to merge two data frames efficiently. Many functions in R that perform these algorithms will perform the sort operation within their function.
0 Comments
Leave a Reply. |
Spatial Ecology @ MSUClick on "Category" below to search for R code compiled by the Zarnetske Spatial & Community Ecology Lab and students in MSU's Spatial Ecology graduate course (FOR870/FW870) Category
All
Archive
October 2016
|