Rearrange the column of the dataframe by column position.

Here, we will rearrange the columns using the index/position of the column. So we will use select method to do this.

Note: index/position  of the column starts with 1

Syntax: select(dataframe.index_positions)

Where,

  • dataframe is the input dataframe
  • index_positions are column positions to be rearranged

Here we are rearranging to different positions.

R




# display actual  dataframe
print("actual  dataframe")
print(data)
  
print("reorder the column with position")
  
# reorder the columns with column positions
# using select
print(select(data,3,1,2))


Output:

Reorder the column of dataframe in R using Dplyr

In this article, we will discuss how to rearrange or reorder the column of the dataframe using dplyr package in R Programming Language.

Creating Dataframe for demonstration:

R




# load the package
library(dplyr)
  
# create the dataframe with three columns
# id , department and salary with 8 rows
data = data.frame(id = c(7058, 7059, 7060, 7089,
                         7072, 7078, 7093, 7034),
                    
                  department = c('IT','sales','finance',
                                 'IT','finance','sales',
                                 'HR','HR'),
                    
                  salary = c(34500.00, 560890.78, 67000.78, 
                             25000.00, 78900.00, 25000.00,
                             45000.00, 90000))
  
# display dataframe
data


Output:

Similar Reads

Method 1: Using select() method

...

Method 2: Rearrange the column of the dataframe by column position.

We are going to use a select() method to reorder columns....

Method 3: Rearrange or Reorder the column name alphabetically

...

Method 4: Rearrange or Reorder the column name in alphabetically reverse order

Here, we will rearrange the columns using the index/position of the column. So we will use select method to do this....

Method 5: Move or shift the column to the First position/ last position in R

...

Method 6: Using dplyr arrange()

Here we are using order() function along with select() function to rearrange the columns in alphabetical order. So we will order the columns using colnames function....

Method 7: Using dplyr arrange() and des() method

...

Method 8: Using arrange_all() function in R dplyr

so we will order the columns using colnames function in reverse....

Contact Us