How to Use the relocate() Function in dplyr (With Examples)

How to Easily Rearrange Columns in R Data Frames with dplyr::relocate()

The dplyr package in R is a fundamental tool within the Tidyverse ecosystem, offering a powerful, consistent grammar for data manipulation. One particularly useful function for structural organization is relocate(), designed explicitly to rearrange the column order within a data frame. Effective column ordering is critical for data presentation, especially when preparing datasets for subsequent modeling or visualization steps, where logical data flow is paramount. The relocate() function simplifies this process significantly.

Unlike older methods of column reordering which might require complex subsetting or indexing, relocate() provides a clear, verb-based approach that enhances code readability. This function operates by specifying which columns should be moved and where they should be placed relative to other existing columns. Understanding the syntax and its various arguments allows for precise control over the structure of your dataset, ensuring that key variables are always visible and logically grouped.


The basic structure of the function is relocate(.data, ..., .before = NULL, .after = NULL). The first argument, .data, is the input data frame. The subsequent ellipsis (...) is where you name the columns you intend to move. The real power comes from the optional positional arguments: .before and .after, which dictate the destination based on another column’s name, providing exceptional flexibility compared to simple front or back moves.

The following methods illustrate the four main ways you can use the relocate() function to change column positions:

Method 1: Move One Column to Front

This is the default behavior when no positional arguments (`.before` or `.after`) are specified. Simply naming the column within the relocate() call moves that column to the first position in the data frame.

#move 'x' column to front
df %>% relocate(x)

Method 2: Move Several Columns to Front

To move multiple columns, list them sequentially. They will appear at the front of the data frame in the order they are listed in the function call. All other columns maintain their relative order.

#move 'x' and 'y' columns to front
df %>% relocate(x, y)

Method 3: Move Column to Position After Another Column

Using the .after argument allows for precise placement. The column(s) being moved will be placed immediately following the reference column specified in the .after argument.

#move 'x' column to position after 'y' column
df %>% relocate(x, .after=y)

Method 4: Move Column to Position Before Another Column

The .before argument positions the moved column(s) directly preceding the specified reference column. This provides flexibility for inserting variables mid-frame.

#move 'x' column to position before 'y' column
df %>% relocate(x, .before=y)

Setting Up the Example Data Frame

To demonstrate the utility and flexibility of the relocate() function, we will first establish a sample data frame in R. This dataset represents performance metrics for several sports teams, featuring columns for team identifiers, points, assists, and rebounds. Consistent use of a standardized dataset across all examples helps illustrate the exact changes implemented by each variation of the relocate() command.

We utilize the base R function data.frame() to construct our example dataset, which will then be passed to the dplyr pipeline using the pipe operator (%>%). This piping syntax is canonical within the Tidyverse and allows for chained operations, making the data workflow extremely intuitive.

Observe the initial structure of the data frame below. Note the original column order: team, points, assists, and rebounds. Our subsequent goal is to systematically alter this established order using various applications of relocate().

#create dataset
df <- data.frame(team=c('A', 'A', 'A', 'B', 'B', 'C', 'C'),
                 points=c(1, 2, 3, 4, 5, 6, 7),
                 assists=c(1, 5, 2, 3, 2, 2, 0),
                 rebounds=c(6, 6, 10, 12, 8, 8, 3))

#view dataset
df

  team points assists rebounds
1    A      1       1        6
2    A      2       5        6
3    A      3       2       10
4    B      4       3       12
5    B      5       2        8
6    C      6       2        8
7    C      7       0        3

Example 1: Moving a Single Column to the Front

The simplest application of the relocate() function involves moving a specified column to the very beginning of the data frame. By default, if no .before or .after arguments are provided, the function assumes the user intends to place the selected column(s) in the first position. This is particularly useful when a key identifier or primary variable needs to be immediately visible for quick reference or inspection.

To achieve this, we simply pass the column name we wish to move directly to the function as the primary argument. We will use the assists column as an example, repositioning it from its original third place to the leading position. Notice how the subsequent columns shift automatically to accommodate the change.

This implementation clearly shows the intent: prioritize the assists variable. The code requires minimal syntax and is highly readable.

#move 'assists' column to front
df %>% relocate(assists)

  assists team points rebounds
1       1    A      1        6
2       5    A      2        6
3       2    A      3       10
4       3    B      4       12
5       2    B      5        8
6       2    C      6        8
7       0    C      7        3

Example 2: Moving Multiple Columns to the Front

The power of relocate() allows efficient handling of multiple columns simultaneously. If you need several variables to appear at the start of your data frame, you can list them sequentially within the function arguments. The order in which you list these columns dictates their new arrangement at the beginning of the frame.

For this example, we place both points and assists before the team column. Since points is listed first, it takes the absolute first position, and assists takes the second. All remaining, unselected columns retain their relative order among themselves but are shifted back after the newly relocated variables.

This capability is invaluable during initial data exploration, where analysts often wish to group related metric variables (like points and assists) ahead of categorical or identifier variables, supporting the principles of tidy data analysis championed by the Tidyverse.

#move 'points' and 'assists' to front
df %>% relocate(points, assists)

  points assists team rebounds
1      1       1    A        6
2      2       5    A        6
3      3       2    A       10
4      4       3    B       12
5      5       2    B        8
6      6       2    C        8
7      7       0    C        3

Example 3: Placing Columns After a Specified Column (.after)

To achieve precise placement after a reference column, we utilize the .after argument. This is crucial when maintaining logical groupings—for example, ensuring that an identifier field immediately follows key performance metrics.

The syntax requires listing the column(s) to be moved first, followed by the positional argument .after = [reference_column]. In this example, we move the team identifier column so it appears directly after the assists column, even though team was originally at the very beginning of the data frame.

Using .after provides a declarative way to structure the data, greatly improving maintainability compared to hardcoding column indices, which can break if the input data schema changes. We are effectively telling dplyr: “Move team, and place it right after assists.”

#move 'team' column to after 'assists' column
df %>% relocate(team, .after=assists)

  points assists team rebounds
1      1       1    A        6
2      2       5    A        6
3      3       2    A       10
4      4       3    B       12
5      5       2    B        8
6      6       2    C        8
7      7       0    C        3

Example 4: Placing Columns Before a Specified Column (.before)

The .before argument provides the inverse functionality: relocating specified columns so that they precede a chosen reference column. This is useful when you need to insert new columns or reposition existing ones immediately upstream of a final processing or output variable.

The structure is identical to Method 3, substituting the positional argument: relocate([column_to_move], .before = [reference_column]). By utilizing this argument, we can enforce a specific sequence crucial for visualization tools or APIs that require inputs in a rigid order.

Here, we demonstrate moving the team column such that it appears directly before the rebounds column. This is an example of moving a column from the front of the data frame to an interior position based on a known endpoint. The resulting structure ensures that the team identifier is adjacent to the rebounds metric.

#move 'team' column to before 'rebounds' column
df %>% relocate(team, .before=rebounds)

  points assists team rebounds
1      1       1    A        6
2      2       5    A        6
3      3       2    A       10
4      4       3    B       12
5      5       2    B        8
6      6       2    C        8
7      7       0    C        3

Summary of relocate() Functionality

The relocate() function offers a streamlined and highly readable method for reorganizing columns in R. By leveraging the principles of the dplyr package, it ensures that data preparation steps are clearly documented and easy to follow. The core versatility lies in its ability to handle both simple front-loading operations and precise positional placements using reference columns.

Below is a summary of the key methods and their corresponding effects, illustrating the core logic of column reordering:

  • Move to Front (Default): Providing only the column names moves them to the beginning. Example: df %>% relocate(A, B)

  • Move After Reference: Using .after positions the moved columns immediately following a specified reference column. Example: df %>% relocate(A, .after = Z)

  • Move Before Reference: Using .before positions the moved columns immediately preceding a specified reference column. Example: df %>% relocate(A, .before = Z)

By integrating relocate() into your data cleaning workflow, you ensure that your datasets are not only structurally sound but also optimized for subsequent analysis and communication, embodying the efficiency and clarity that the dplyr approach promotes.

The following tutorials explain how to perform other common functions using dplyr:

Cite this article

stats writer (2025). How to Easily Rearrange Columns in R Data Frames with dplyr::relocate(). PSYCHOLOGICAL SCALES. Retrieved from https://scales.arabpsychology.com/stats/how-to-use-the-relocate-function-in-dplyr-with-examples/

stats writer. "How to Easily Rearrange Columns in R Data Frames with dplyr::relocate()." PSYCHOLOGICAL SCALES, 1 Dec. 2025, https://scales.arabpsychology.com/stats/how-to-use-the-relocate-function-in-dplyr-with-examples/.

stats writer. "How to Easily Rearrange Columns in R Data Frames with dplyr::relocate()." PSYCHOLOGICAL SCALES, 2025. https://scales.arabpsychology.com/stats/how-to-use-the-relocate-function-in-dplyr-with-examples/.

stats writer (2025) 'How to Easily Rearrange Columns in R Data Frames with dplyr::relocate()', PSYCHOLOGICAL SCALES. Available at: https://scales.arabpsychology.com/stats/how-to-use-the-relocate-function-in-dplyr-with-examples/.

[1] stats writer, "How to Easily Rearrange Columns in R Data Frames with dplyr::relocate()," PSYCHOLOGICAL SCALES, vol. X, no. Y, ص Z-Z, December, 2025.

stats writer. How to Easily Rearrange Columns in R Data Frames with dplyr::relocate(). PSYCHOLOGICAL SCALES. 2025;vol(issue):pages.

Download Post (.PDF)
Slide Up
x
PDF
Scroll to Top