R Program to Reorder Columns in a Dataframe

Example 1: Reorder R Dataframe Columns Using Column Name

# import dplyr package
library(dplyr)

# Create a data frame
dataframe1 <- data.frame (
  Age = c(22, 15, 19),
  Address = c("Nepal", "USA", "Germany"),
  Name = c("Juan", "Alcaraz", "Simantha")
)

# rearrange columns in Name, Age, Address order
print(select(dataframe1, Name, Age, Address))

Output

     Name Age Address
1     Juan  22   Nepal
2  Alcaraz  15     USA
3 Simantha  19 Germany

In the above example, we have used the select() function provided by the dplyr package to reorder columns of the dataframe named dataframe1.

select(dataframe1, Name, Age, Address)

Here, inside select(),

  • dataframe1 - a dataframe whose column is to be reordered
  • Name, Age, Address - new order of columns

Hence the order of dataframe1 column is changed from Age, Address, Name to Name Age Address.


Example 2: Reorder R Dataframe Columns by Column Position

# import dplyr package
library(dplyr)

# Create a data frame
dataframe1 <- data.frame (
  Age = c(22, 15, 19),
  Address = c("Nepal", "USA", "Germany"),
  Name = c("Juan", "Alcaraz", "Simantha")
)

# rearrange columns in Name, Age, Address order
print(select(dataframe1, 3, 1, 2))

Output

     Name Age Address
1     Juan  22   Nepal
2  Alcaraz  15     USA
3 Simantha  19 Germany

In the above example, we have used the column position inside select() to reorder columns of dataframe1.

select(dataframe1, 3, 1, 2)

Here, the 3rd column is now 1st column, 1st column is now 2nd column and 2nd column is now 3rd column.