How To Change Order of Columns in R

When doing data science with r programming, it is sometimes necessary to change order of columns in r. This is because a dataframe is not always created with its columns in the order that we need them. Fortunately, r offers several ways of carrying out this task. It is easy to do once you know how to do it.

General Ways to Change Order of Columns in Base R

There are several base r ways to reorder column names. This process can involve a complete change in column order or simply moving around a single column. You can use the subset function or column references in brackets next to the data frame name. When using the data frame name with brackets you can use a vector of column numbers or column names.

Explanation (Change Order of Columns in R)

With these three methods you can easily change the column position of any single column in a multiple column data frame. All three methods use a vector to define the new column order. You can arrange them based on column name or number. You can base the new column order on any sort order that you want. You can even place the columns in random order.

Examples (Change Order of Columns in R)

Here we have examples of three separate methods for changing the order of the columns in a data frame.

> df = data.frame(x = c(1,2,3,4,5),
+ z = c(“A”,”B”,”C”,”D”,”E”),
+ y = c(2,3,4,5,6))
> df
x z y
1 1 A 2
2 2 B 3
3 3 C 4
4 4 D 5
5 5 E 6
> df[c(2,1,3)]
z x y
1 A 1 2
2 B 2 3
3 C 3 4
4 D 4 5
5 E 5 6

Here the example data is reorganized by using a vector of the numerical representation of the original column order.

> df = data.frame(x = c(1,2,3,4,5),
+ z = c(“A”,”B”,”C”,”D”,”E”),
+ y = c(2,3,4,5,6))
> df
x z y
1 1 A 2
2 2 B 3
3 3 C 4
4 4 D 5
5 5 E 6
> df[c(“z”,”x”,”y”)]
z x y
1 A 1 2
2 B 2 3
3 C 3 4
4 D 4 5
5 E 5 6

Here the example data is reorganized by using a column name vector.

> df = data.frame(x = c(1,2,3,4,5),
+ z = c(“A”,”B”,”C”,”D”,”E”),
+ y = c(2,3,4,5,6))
> df
x z y
1 1 A 2
2 2 B 3
3 3 C 4
4 4 D 5
5 5 E 6
> subset(df, select = c(2,1,3))
z x y
1 A 1 2
2 B 2 3
3 C 3 4
4 D 4 5
5 E 5 6

Here the example data is reorganized by using the subset function.

Application

All three methods are convenient ways to alter table variable order. Rearranging data frame columns allows you to arrange them in any order that is convenient for your analysis. One of the advantages of such rearrangements is that different column orders can supply different ways of seeing the data. This may not make sense to someone with little experience, but the order in which data is presented can affect how you see it.

Changing column order in r is a process that has several convenient methods for you to use. Not only can it help you to see the data in unusual ways, but it allows you to create a column order that is more convenient for your data processing.

Scroll to top
Privacy Policy