While working on data analysis, it is very common to need "Reordering Columns in R" to meet the requirements of a table. After reordering a few columns, it becomes much easier to read and filter data from a large table or data frame.
Reordering the columns of a table improves readability and makes a bigger project easier to work with. It is simple to reorder columns using the R programming language. All you need is a grasp of the basics, and you're good to go.
This article describes the different methods to reorder the columns of a table in the R programming language, from base R to the dplyr and data.table packages. Every example here is a complete script you can paste into RStudio (we used R 4.3, dplyr 1.1.4, and data.table 1.14). So, let's start our discussion.
Summary Or Key Highlights:
- Reordering columns is done on a data frame, the main table structure in R.
- In base R, you reorder columns with square brackets, either by name or by position, or with the
subset()function. - The dplyr package gives you
select()andrelocate().relocate()is the easiest way to move one or two columns without listing all of them. - The data.table package has
setcolorder(), which changes the table in place. - Columns can also be rearranged in alphabetical order.
- From data processing to data visualization, rearranging the columns of a table comes up often.
What Is A Data Frame In R Programming Language?
A data frame is the tabular format in the R programming language, and it works like a spreadsheet inside your program. Each column holds one variable, and each row holds one record. Most tables you create or read from a CSV file in R will be data frames.
Behind the scenes, a data frame is a list of columns, where every column has the same length. This is why reordering columns is so easy in R: you are just changing the order of the items in that list.
Let us first see how to define a simple data frame in the R programming language.
# Single-Column Data Frame, Written Two Ways
df <- data.frame(A = c(1, 2, 3))
df2 <- data.frame(A = 1:3)
print(df)
print(identical(df$A, as.numeric(df2$A))) # Same Values, Different Type
str(df2)
Output:
A 1 1 2 2 3 3 [1] TRUE 'data.frame': 3 obs. of 1 variable: $ A: int 1 2 3
The first two lines both create a single-column data frame. The values are the same, but c(1, 2, 3) stores them as doubles (type numeric), while 1:3 stores them as integers, which you can see in the str() output. We will create data frames in the same way to try out each method of reordering columns in R.
How To Reorder Columns In An R Data Frame?
Now, it is time to work on the central part of this topic. Here, we will go through the ways to rearrange the columns of a table in the R programming language. These are the methods used most often.
We will start with the manual method, using column names. Later, we will discuss a few more ways to reach the same goal. So, let us start the practical part.
Method 1: By Name Of The Column
Here, the column names are used to change the column positions in the data frame. Inside the square brackets, the part before the comma picks rows, and the part after the comma picks columns. If we leave the row part empty and list the column names in a new order, R returns the columns in that order.
Syntax: FrameName[, c("Column Names In New Order")]
# Creating A Sample Data Frame (DF)
zap <- data.frame(A = c(101, 202, 303),
B = c(404, 505, 606),
C = c(707, 808, 909))
print(zap)
zap <- zap[, c("B", "C", "A")] # Reordering Table
print(zap)
Steps Of The Program:
- We declare a sample table with three columns, A, B, and C.
- Now, we print the original table to see the changes later.
- Using the above syntax, we change the column order in the table. Here, the 2nd column becomes the first one.
- We print the table again to check the result.
Output:
A B C
1 101 404 707
2 202 505 808
3 303 606 909
B C A
1 404 707 101
2 505 808 202
3 606 909 303
From the above example, we can see that the structure of the first table is different from the second one. Column B is now in the first position, and column C is now in the second position. This means our code is successful.
Method 2: By Column Position (Index)
If you know where the columns are, you can use their position numbers instead of their names. The first column is 1, the second is 2, and so on.
zap <- data.frame(A = c(101, 202, 303),
B = c(404, 505, 606),
C = c(707, 808, 909))
print(zap[, c(3, 1, 2)]) # Column Positions Instead Of Names
print(zap[, rev(seq_along(zap))]) # Reverse The Whole Order
Output:
C A B
1 707 101 404
2 808 202 505
3 909 303 606
C B A
1 707 404 101
2 808 505 202
3 909 606 303
c(3, 1, 2) means "third column, then first, then second". The second table uses rev(seq_along(zap)), which produces 3, 2, 1, to reverse the whole order without typing the numbers yourself.
Positions are quick to type, but be careful: if someone adds a column to the data later, the positions shift, and your code silently picks the wrong columns. Names are safer for anything you will reuse.
Method 3: Using The Base subset() Function
Here, we use a simple base R function, subset(). With subset(), we can quickly change the column order in the table. Note the syntax below for the code to run successfully.
Syntax: subset(FrameName, select = c(Column Name Sequence))
# Creating A Sample Data Frame (DF)
zap <- data.frame(A = c(100, 200, 300),
B = c(400, 500, 600),
C = c(700, 800, 900))
print(zap)
one <- subset(zap, select = c(C, A, B)) # Reordering Table
print(one)
Steps Of The Program:
- The first step is to declare a table with some column names and values.
- Now, the table is printed before making any changes.
- Using the above syntax, we make the changes. You can put the columns in any order you like.
- Now, we print the table again.
Output:
A B C
1 100 400 700
2 200 500 800
3 300 600 900
C A B
1 700 100 400
2 800 200 500
3 900 300 600
From the above example, we can see that there is a clear difference between the first table and the last table. The last table follows the sequence that we gave in select. The first table keeps the original order. Notice that inside subset(), the column names don't need quotes.
Method 4: Using The dplyr Package (select)
Another great way to rearrange columns in the R programming language is the dplyr package. It is a package made for data manipulation, and it is part of the tidyverse. If you haven't installed it yet, run install.packages("dplyr") once.
Syntax: select(FrameName, all_of(Desired Sequence))
suppressPackageStartupMessages(library(dplyr)) # Loading The Package
# Creating A Sample Data Frame (DF)
zap <- data.frame(A = c(101, 202, 303),
B = c(404, 505, 606),
C = c(707, 808, 909))
do <- c("C", "A", "B") # The Desired Order
one <- select(zap, all_of(do)) # Reordering Table
print(one)
Steps Of The Program:
- At first, we load the dplyr package into the program to use its functions. (
suppressPackageStartupMessages()only hides the loading messages.) - Now, a table is created with some values.
- Here, we create another variable that stores the desired sequence of the new table.
- Now, we use the above syntax to make the changes.
all_of()tellsselect()that the names come from a variable. - Now, we print the new table with its changes.
Output:
C A B 1 707 101 404 2 808 202 505 3 909 303 606
The above example clearly shows that the new table follows the desired sequence. One easy slip here: printing zap instead of one shows the old order, because select() never changes the original table. Always print the variable that holds the result.
Method 5: Move Just One Or Two Columns With relocate()
All the methods so far need you to list every column. That is fine for three columns, but real datasets often have twenty or more. Most of the time, you only want to move one column, like bringing the ID to the front. dplyr has two easy ways to do this:
suppressPackageStartupMessages(library(dplyr))
students <- data.frame(
name = c("Ava", "Ben", "Cara"),
major = c("CS", "Math", "CS"),
exam1 = c(88, 75, 93),
exam2 = c(91, 80, 85),
id = c(1003, 1001, 1002)
)
# Move One Column To The Front, Keep Everything Else As It Is
print(select(students, id, everything()))
# relocate() Does The Same Without Listing Anything Else
print(relocate(students, id))
# Put A Column Right After Another One
print(relocate(students, id, .after = name))
# Send A Column To The End
print(relocate(students, major, .after = last_col()))
Output:
id name major exam1 exam2
1 1003 Ava CS 88 91
2 1001 Ben Math 75 80
3 1002 Cara CS 93 85
id name major exam1 exam2
1 1003 Ava CS 88 91
2 1001 Ben Math 75 80
3 1002 Cara CS 93 85
name id major exam1 exam2
1 Ava 1003 CS 88 91
2 Ben 1001 Math 75 80
3 Cara 1002 CS 93 85
name exam1 exam2 id major
1 Ava 88 91 1003 CS
2 Ben 75 80 1001 Math
3 Cara 93 85 1002 CS
select(students, id, everything())putsidfirst, andeverything()means "all the other columns, in their current order".relocate(students, id)does the same thing, and it is the more readable choice in dplyr 1.0.0 and later..after = nameplaces the column right after another column. There is also.before..after = last_col()sends a column to the very end.
relocate() can also move columns by type or by name pattern, which is very handy on wide datasets:
suppressPackageStartupMessages(library(dplyr))
students <- data.frame(
name = c("Ava", "Ben", "Cara"),
exam1 = c(88, 75, 93),
major = c("CS", "Math", "CS"),
exam2 = c(91, 80, 85)
)
# All Text Columns First, Then The Numbers
print(relocate(students, where(is.character)))
# All Columns Whose Name Starts With "exam" Go To The Front
print(relocate(students, starts_with("exam")))
Output:
name major exam1 exam2 1 Ava CS 88 91 2 Ben Math 75 80 3 Cara CS 93 85 exam1 exam2 name major 1 88 91 Ava CS 2 75 80 Ben Math 3 93 85 Cara CS
If you are not using dplyr, you can move one column to the front in base R by combining its name with setdiff(), which returns all the other names:
students <- data.frame(
name = c("Ava", "Ben", "Cara"),
major = c("CS", "Math", "CS"),
exam1 = c(88, 75, 93),
id = c(1003, 1001, 1002)
)
# Base R: "id" First, Then Every Other Column In Its Old Order
students <- students[, c("id", setdiff(names(students), "id"))]
print(students)
Output:
id name major exam1 1 1003 Ava CS 88 2 1001 Ben Math 75 3 1002 Cara CS 93
Method 6: Using setcolorder() From data.table
If you work with large datasets, you may be using the data.table package. Its setcolorder() function reorders the columns in place. That means it changes the table itself, without making a copy, so you don't need <-.
library(data.table)
DT <- data.table(name = c("Ava", "Ben"), exam1 = c(88, 75), id = c(1003, 1001))
setcolorder(DT, c("id", "name", "exam1")) # Changes DT Itself, No <- Needed
print(DT)
setcolorder(DT, "exam1") # Partial Order: exam1 First, Rest Keep Their Order
print(DT)
Output:
id name exam1 1: 1003 Ava 88 2: 1001 Ben 75 exam1 id name 1: 88 1003 Ava 2: 75 1001 Ben
In the second call, we only named exam1. data.table moved it to the front and kept the other columns in their existing order. Newer versions of data.table (1.15.0 and later) also accept before = and after = arguments, similar to relocate().
How To Rearrange Columns In R Alphabetically?
Now that we have covered the core methods, let us look at a few more common questions about changing column order in R. Here, we will rearrange the columns in alphabetical order.
For that, the following syntax is used. names() gives the column names, and order() returns the positions that would sort them, which we then use inside the square brackets.
Syntax: FrameName[, order(names(FrameName))]
# Creating A Sample Data Frame (DF)
zap <- data.frame(B = c(100, 200, 300),
C = c(400, 500, 600),
A = c(700, 800, 900))
zap <- zap[, order(names(zap))] # Reordering Table
print(zap)
print(zap[, order(names(zap), decreasing = TRUE)]) # Z To A
Steps Of The Program:
- Here, the table is created with some values. The column names are not in alphabetical order, because we want to fix that with code.
- Now, the above syntax is used to change the order in the same table.
- Now, the table is printed to check the result.
- At last,
decreasing = TRUEgives the reverse order, from Z to A.
Output:
A B C
1 700 100 400
2 800 200 500
3 900 300 600
C B A
1 400 100 700
2 500 200 800
3 600 300 900
The above example shows that the table columns are now in alphabetical order. Earlier, the columns were in random order.
One thing to watch: when column names mix uppercase and lowercase letters, the sorted order can depend on your computer's language settings (the "locale"):
df <- data.frame(b = 1, Apple = 2, a = 3, Banana = 4)
print(names(df)[order(names(df))]) # Depends On Your Locale
print(names(df)[order(names(df), method = "radix")]) # Always C Order: Capitals First
print(names(df)[order(tolower(names(df)))]) # Ignore Case On Purpose
Output (on a US English system):
[1] "a" "Apple" "b" "Banana" [1] "Apple" "Banana" "a" "b" [1] "a" "Apple" "b" "Banana"
On a typical US English setup, order() sorts letters together, so "a" and "Apple" sit next to each other. With method = "radix" (and on some Linux servers by default), every capital letter comes before every lowercase letter. If your assignment output must match exactly, sort with tolower() so the result is the same on every computer.
How To Reorder Columns In R Based On A List Of Names?
Often, the order you want is already stored somewhere, like a vector of names your instructor gave you, or the column order of another data frame. In that case, store the desired sequence in a variable and use it inside the square brackets.
# Creating A Sample Data Frame (DF)
zap <- data.frame(C = c(101, 202, 303),
A = c(404, 505, 606),
B = c(707, 808, 909))
do <- c("A", "C", "B") # Desired Order
zap <- zap[, do] # Reordering Table
print(zap)
Steps Of The Program:
- The table is created with some values to work on.
- Then, the desired sequence is written in the program using the column names.
- Now, we apply the changes to the table using the variable
do. - At last, the changed table is printed on the screen.
Output:
A C B 1 404 101 707 2 505 202 808 3 606 303 909
The above example shows that the table can be reordered using a stored sequence. The new table has column C in the middle, after A and before B, which is exactly what we wanted. A common use of this: to make one data frame use the same column order as another, for example before exporting both to the same file, write df2 <- df2[, names(df1)].
Comparing The Ways To Reorder Columns In R
| Method | Best For | Needs A Package? | Watch Out For |
|---|---|---|---|
df[, c("B", "A")] | Small tables, full new order | No | One column returns a vector (see below) |
df[, c(2, 1)] | Quick checks | No | Breaks if columns are added later |
subset(df, select = ...) | Readable base R code | No | Meant for interactive use, not functions |
select() | Full order inside a dplyr pipeline | dplyr | Columns you don't list are dropped |
relocate() | Moving one or a few columns | dplyr | Use only one of .before or .after |
setcolorder() | Large data.tables | data.table | Changes the original table in place |
Common Mistakes When Reordering Columns In R
Here are the mistakes that trip up students most often with this topic. The first one causes confusing errors later in the code, not at the line where it happens:
zap <- data.frame(A = c(101, 202, 303),
B = c(404, 505, 606))
one <- zap[, "B"] # Only One Column Selected
print(one)
print(class(one))
two <- zap[, "B", drop = FALSE] # Keeps It A Data Frame
print(two)
print(class(two))
Output:
[1] 404 505 606
[1] "numeric"
B
1 404
2 505
3 606
[1] "data.frame"
When you pick just one column with square brackets, R simplifies the result into a plain vector, and the column name is gone. Add drop = FALSE to keep it as a data frame.
The second is a typo in a column name. Base R stops with a short error that doesn't tell you which name is wrong:
zap <- data.frame(A = 1:2, B = 3:4, C = 5:6)
zap[, c("B", "c", "A")] # Lowercase "c" Does Not Exist
Output:
Error in `[.data.frame`(zap, , c("B", "c", "A")) :
undefined columns selected
dplyr is more helpful here. any_of() quietly skips names that don't exist, while all_of() stops and tells you exactly which column is missing:
suppressPackageStartupMessages(library(dplyr))
zap <- data.frame(A = 1:2, B = 3:4, C = 5:6)
print(select(zap, any_of(c("B", "c", "A")))) # any_of() Skips Missing Names
select(zap, all_of(c("B", "c", "A"))) # all_of() Stops With An Error
Output:
B A 1 3 1 2 4 2 Error in `all_of()`: ! Can't subset columns that don't exist. ✖ Column `c` doesn't exist.
Column names in R are case-sensitive, so "c" and "C" are different columns. A few smaller slips cause most of the remaining bugs:
- Forgetting to save the result with
<-. Except forsetcolorder(), none of these methods change the original data frame. - Using
select()to move one column and accidentally dropping all the others. Addeverything(), or userelocate(). - Reordering by position in a script, then adding a column to the data and getting the wrong columns without any error.
Reordering is usually one step in a longer R assignment. When the rest of the pipeline is the hard part, an R programming expert can explain each step of your code.
Practical Examples And Applications Of Column Reordering In R
Before we finish, let us look at where column reordering is actually used in real work.
- Data Processing: Column reordering is done a lot in data processing. You start with a raw dataset, pull out the columns you need, and put the key columns, like IDs and dates, first so the table is easy to check.
- Data Visualization: Before making a chart or a table for a report, columns are reordered so the most important ones appear first and the output reads in a logical order.
- Reshaping Data: When a dataset is reshaped for another purpose, like matching the layout of another file, the columns are reordered so both tables line up. (
rbind()on data frames matches columns by name, but appending to a CSV file or binding matrices goes by position.) - Exporting: When you save a data frame with
write.csv(), the columns are written in their current order, so reorder first if the file must match a required layout.
If you want to practice these skills on a bigger dataset, our list of R projects for students and beginners is a good place to start. And for a next step in data analysis, see how to build a decision tree in R.
Conclusion
As we saw, it is very important to understand how "Reordering Columns in R" works.
With these methods, you can change the layout of any table created in the R programming language. For a quick change, square brackets with column names are enough. For moving one column in a big table, relocate() saves a lot of typing.
It is also recommended to build a strong understanding of the basics of R, like vectors, data frames, and indexing. Without that foundation, the methods in this article can feel like magic syntax to memorize, and it becomes hard to apply them on your own.
Takeaways:
- Reordering columns means changing the column positions in a data frame so the data you need is where you want it.
- In base R, use square brackets with names, positions, or
order(names(df))for alphabetical order. - In dplyr, use
select()for a full new order andrelocate()to move just a few columns. - In data.table,
setcolorder()reorders the table in place. - Selecting one column with brackets returns a vector unless you add
drop = FALSE. - Reordering is used everywhere from data cleaning to visualization and exporting.
Frequently Asked Questions
How do I move a column to the first position in R?
With dplyr, use relocate(df, column_name). In base R, use df[, c("column_name", setdiff(names(df), "column_name"))]. Both keep all the other columns in their original order.
How do I move a column to the end of a data frame in R?
With dplyr, use relocate(df, column_name, .after = last_col()). In base R, use df[, c(setdiff(names(df), "column_name"), "column_name")].
How do I sort the columns of a data frame alphabetically in R?
Use df[, order(names(df))]. Add decreasing = TRUE for Z to A. If the names mix uppercase and lowercase letters, use order(tolower(names(df))) so the result is the same on every computer.
Why did my data frame turn into a vector after reordering?
When you select a single column with square brackets, R simplifies it to a vector. Write df[, "column", drop = FALSE] to keep it as a data frame.
What is the difference between select() and relocate() in dplyr?
select() keeps only the columns you name, in the order you name them, so it can drop columns. relocate() only moves the columns you name and keeps every other column in the data frame.
Does reordering columns change the original data frame?
No, not with base R or dplyr. They return a new data frame, so you must save it with <-. The exception is setcolorder() from data.table, which changes the table in place.

