# arrange Function of dplyr R Package (2 Examples)

In this R article you’ll learn how to **order data sets with the arrange function** of the dplyr package.

Table of contents:

- Example Data
- Example 1: Arrange Data By One Variable
- Example 2: Arrange Data By Multiple Variables
- Video, Further Resources & Summary

Let’s start right away!

## Example Data

In the examples of this tutorial, we’ll use the following data frame:

data <- data.frame(x1 = 1:5, # Create example data x2 = c(1, 2, 2, 1, 2), x3 = c("B", "C", "E", "A", "D")) data # Print data to RStudio console # x1 x2 x3 # 1 1 1 B # 2 2 2 C # 3 3 2 E # 4 4 1 A # 5 5 2 D

Our example data frame contains five rows and three columns with the names x1, x2, and x3. The columns x2 and x3 are not sorted.

Furthermore, we have to install and load the dplyr package in RStudio, in order to be able to apply the arrange function of the dplyr package:

install.packages("dplyr") # Install dplyr package library("dplyr") # Load dplyr package

Now, let’s move on to the examples!

## Example 1: Arrange Data By One Variable

Example 1 shows how to order the rows of a data frame (or tibble) based on one variable. If we want to order our data according to the variable x2, we can apply the arrange command as follows:

arrange(data, x2) # Arrange data by one column # x1 x2 x3 # 1 1 1 B # 2 4 1 A # 3 2 2 C # 4 3 2 E # 5 5 2 D

As you can see based on the RStudio console output, the rows of our data were sorted descendingly according to the values of the variable x2. However, you can also see that the values of the column x3 are still unordered.

## Example 2: Arrange Data By Multiple Variables

If we want to arrange our data frame according to several columns, we can simply specify multiple variable names within the arrange function. Have a look at the following R code:

arrange(data, x2, x3) # Arrange data by multiple columns # x1 x2 x3 # 1 4 1 A # 2 1 1 B # 3 2 2 C # 4 5 2 D # 5 3 2 E

As you can see, our data was rearranged so that it is sorted according to x2 AND x3.

## Video, Further Resources & Summary

Do you need further explanations on the R programming syntax of this article? Then I can recommend to watch the following video of my YouTube channel. I’m explaining the R code of this post in the video.

Furthermore, you could have a look at the related posts on this homepage.

- R dplyr Package Introduction
- Reorder Columns of Data Frame in R
- R Functions List (+ Examples)
- The R Programming Language

Summary: At this point you should know how to **reorder the rows of a data frame or tibble** in the R programming language. Please tell me about it in the comments section below, if you have further questions.