使用 Dplyr 在 R 中对 DataFrame 进行排序
在本文中,我们将讨论如何使用 Dplyr 包在 R 编程语言中对数据帧进行排序。中的R编程语言中的包Dplyr提供了一个函数调用安排()函数,它是用于排序的数据帧是有用的。
句法 :
arrange(.data, …)
下面给出的方法显示了如何以各种方式使用此函数对数据帧进行排序。
按升序排序
按升序排序是排列()函数的默认排序顺序。排序依据的属性应作为此函数的参数给出。
示例:按升序对数据框进行排序
R
# Installing the loading the package
install.packages("dplyr")
library(dplyr)
# Creating dataframe
gfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera",
"Sehnaaz", "Joe","Raj", "Simran",
"Priya","Tejaswi"),
Product = c("Product A", "Product B", "Product C",
"Product A", "Product D", "Product B",
"Product D", "Product C", "Product D",
"Product A"),
Salary = c(514.65, 354.99, 345.44, 989.56, 767.50,
576.90, 878.67, 904.56,123.45, 765.78)
)
gfg
# Sorting the dataframe in ascending order
arrange(gfg, Salary)
R
library(dplyr)
# Creating dataframe
gfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera",
"Sehnaaz", "Joe", "Raj", "Simran",
"Priya", "Tejaswi"),
Product = c("Product A", "Product B", "Product C",
"Product A", "Product D", "Product B",
"Product D", "Product C", "Product D",
"Product A"),
Salary = c(514.65, 354.99, 345.44, 989.56, 767.50,
576.90, 878.67, 904.56,123.45, 765.78))
# Sorting the dataframe in descending
# order
gfg %>% arrange(desc(Salary))
R
library(dplyr)
# Creating dataframe
gfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera",
"Sehnaaz", "Joe", "Raj", "Simran",
"Priya", "Tejaswi"),
Product = c("Product A", "Product B", "Product C",
"Product A", "Product D", "Product B",
"Product D", "Product C", "Product D",
"Product A"),
Salary = c(514.65, 354.99, 345.44, 989.56, 767.50,
576.90, 878.67, 904.56,123.45, 765.78))
# Sorting the dataframe using
# multiple variables
gfg %>% arrange(Product, desc(Salary))
输出 :
按降序排序
为了按降序对我们的数据帧进行排序,我们将使用 desc()函数和排列 ()函数。我们还将使用 %运算符来比较我们用于排序目的的数据框列。
示例:按降序对数据框进行排序
电阻
library(dplyr)
# Creating dataframe
gfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera",
"Sehnaaz", "Joe", "Raj", "Simran",
"Priya", "Tejaswi"),
Product = c("Product A", "Product B", "Product C",
"Product A", "Product D", "Product B",
"Product D", "Product C", "Product D",
"Product A"),
Salary = c(514.65, 354.99, 345.44, 989.56, 767.50,
576.90, 878.67, 904.56,123.45, 765.78))
# Sorting the dataframe in descending
# order
gfg %>% arrange(desc(Salary))
输出 :
使用多个变量对数据框进行排序
我们现在将使用排列()函数使用多个变量对我们的数据框进行排序。属性应该被赋予由一列分隔的函数。例如,在给定的示例中,数据框按降序的薪水列和升序的产品列排序。我们将使用 %运算符来比较要按降序排序的数据。
示例:使用多个变量对数据框进行排序
电阻
library(dplyr)
# Creating dataframe
gfg = data.frame(Customers = c("Roohi", "James", "Satish", "Heera",
"Sehnaaz", "Joe", "Raj", "Simran",
"Priya", "Tejaswi"),
Product = c("Product A", "Product B", "Product C",
"Product A", "Product D", "Product B",
"Product D", "Product C", "Product D",
"Product A"),
Salary = c(514.65, 354.99, 345.44, 989.56, 767.50,
576.90, 878.67, 904.56,123.45, 765.78))
# Sorting the dataframe using
# multiple variables
gfg %>% arrange(Product, desc(Salary))
输出 :