Sorting Data in R
To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order. Here are some examples.
Run this code{:style="position: absolute; top: 0; right: 0; border-radius: 2px; background: rgba(3, 239, 98);font-weight: 600; text-decoration: none;" target="_blank"}
# sorting examples using the mtcars dataset
attach(mtcars)
# sort by mpg
newdata <- mtcars[order(mpg),]
# sort by mpg and cyl
newdata <- mtcars[order(mpg, cyl),]
#sort by mpg (ascending) and cyl (descending)
newdata <- mtcars[order(mpg, -cyl),]
detach(mtcars)
To practice, try this sorting exercise with the order() function.