Tips for Rearranging Columns in R, you might frequently want to reorder the columns in a data frame.
The select() function from the dplyr package, fortunately, makes this simple to accomplish.
This tutorial shows several examples of how to use this function in practice using the following data frame.
Let’s create a data frame
df <- data.frame(player = c('P1', 'P2', 'P3', 'P4'), points = c(124, 229, 313, 415), result = c('Win', 'Loss', 'Win', 'Loss'))
Now we can view the data frame
df player points result 1 P1 124 Win 2 P2 229 Loss 3 P3 313 Win 4 P4 415 Loss
Example 1: A Column is Moved to the First Position
How to shift a particular column in a data frame to the front position is demonstrated by the code below.
Let’s move column ‘result’ to the first position
df %>% select(result, everything()) result player points 1 Win P1 124 2 Loss P2 229 3 Win P3 313 4 Loss P4 415
This code instructs dplyr to initially select the points column before including every other column.
Example 2: Move a Column to the Last Position
How to relocate a particular column in a data frame to the last location is demonstrated by the code below:
relocate ‘player’ column to last place
df %>% select(-player, player) points result player 1 124 Win P1 2 229 Loss P2 3 313 Win P3 4 415 Loss P4
Dplyr is instructed by this code to first choose all columns other than the player column, then to select the player column once more.
The player column is thus moved to the bottom of the data frame as a result of this.
Example 3: Rearrange Several Columns
The code that follows demonstrates how to sequentially reorder multiple columns.
df %>% select(points, result, player) points result player 1 124 Win P1 2 229 Loss P2 3 313 Win P3 4 415 Loss P4
Example 4: Alphabetically reorder the columns
The code below demonstrates how to alphabetically arrange the columns.
alphabetize the columns
df %>% select(order(colnames(.))) player points result 1 P1 124 Win 2 P2 229 Loss 3 P3 313 Win 4 P4 415 Loss
Example 5: Reverse Column Order
Reversing the column order in a data frame is demonstrated by the code below.
column order in reverse
df %>% select(result:player, everything()) result points player 1 Win 124 P1 2 Loss 229 P2 3 Win 313 P3 4 Loss 415 P4