15.6 Reordering Columns in a Data Frame

15.6.1 Problem

You want to change the order of columns in a data frame.

15.6.2 Solution

Use the select() from dplyr.

The new data frame will contain the columns you specified in select(), in the order you specified. Note that select() returns a new data frame, so if you want to change the original variable, you’ll need to save the new result over it.

15.6.3 Discussion

If you are only reordering a few variables and want to keep the rest of the variables in order, you can use everything() as a placeholder:

See ?select_helpers for other ways to select columns. You can, for example, select columns by matching parts of the name.

Using base R, you can also reorder columns by their name or numeric position. This returns a new data frame, which can be saved over the original.

In these examples, I used list-style indexing. A data frame is essentially a list of vectors, and indexing into it as a list will return another data frame. You can get the same effect with matrix-style indexing:

In this case, both methods return the same result, a data frame. However, when retrieving a single column, list-style indexing will return a data frame, while matrix-style indexing will return a vector:

You can use drop=FALSE to ensure that it returns a data frame: