R中数据框重排序

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)

如果数据包含缺失值,它们总是在最后出现。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容