This tutorial describes how to reorder (i.e., sort) rows, in your data table, by the value of one or more columns (i.e., variables).
You will learn how to easily:
Sort a data frame rows in ascending order (from low to high) using the R function arrange() [dplyr package]
Sort rows in descending order (from high to low) using arrange() in combination with the function desc() [dplyrpackage]
library(tidyverse)
my_data <- as_tibble(iris)
my_data
Arrange rows
The dplyr function arrange() can be used to reorder (or sort) rows by one or more variables.
Reorder rows by Sepal.Length in ascending order
my_data %>% arrange(Sepal.Length)
Reorder rows by Sepal.Length in descending order. Use the function desc():
my_data %>% arrange(desc(Sepal.Length))
Instead of using the function desc(), you can prepend the sorting variable by a minus sign to indicate descending order, as follow.
arrange(my_data, -Sepal.Length)
Reorder rows by multiple variables: Sepal.Length and Sepal.width
my_data %>% arrange(Sepal.Length, Sepal.Width)
如果数据包含缺失值,它们总是在最后出现。