What is the arrange() function in R?
The arrange() function in R programming is used to reorder the rows of a data frame/table by using column names. These columns are passed as the expression in the function.
Syntax
The code below uses the arrange() function to arrange a data frame with the dplyr library:
arrange(.data, …)
The code below uses the arrange() function for a grouped data frame:
arrange(.data, …, .by_group= FALSE)
Parameters
.data: The data or table that we want to arrange..group_by: If set totrue,.group_bywill arrange by grouping the variables. This parameter only relates to grouped data frames.…: The list of variables, separated by a comma.
Example 1
In line 4, we create a data frame df that contains fruit names. The quantity_in_kgs vector represents the quantity of the fruit. We can use the arrange() function to arrange the fruit names according to their quantities.
# Load the librarylibrary(dplyr)# Creating the data framedf <- data.frame( fruits = c("Apples", "Mangoes", "Bananas", "Oranges"),quantity_in_kgs = c(8, 3, 12, 10) )# Arrange the data of fruits using quantity_in_kgsdf.fruits<- arrange(df, quantity_in_kgs)print(df.fruits)
Example 2
In the code snippet below, we arrange the data frame according to weight. To achieve this goal, we load the PlantGrowth dataset in y and use the head() method to get the first 6 rows in z. In line 11, we arrange plant groups according to their weights.
# arrange() function to reorder the dataset in R program.# Load the librarylibrary(dplyr)# Call the buildin datasety <- PlantGrowth# get head values 6 rowsz<- head(y)# print values.print(z)# Call the function: arrange()arrange(z, weight)