Re order or Rearrange the column of dataframe in R

Re order or Re arrange the column of the dataframe in R, is accomplished either by column name or by column position. Let’s see how to

  • Re arrange the column of the dataframe by column name.
  • Re arrange the column of the dataframe by column position.

Let’s First create a dataframe

df1 = data.frame( Name = c('George','Andrea', 'Micheal','Maggie','Ravi','Xien','Jalpa'), 
                  Grade_score=c(4,6,2,9,5,7,8),
                  Mathematics1_score=c(45,78,44,89,66,49,72),
                  Science_score=c(56,52,45,88,33,90,47))

df1 will be

Re order or Rearrange the column of dataframe in R 1

 

Re arrange the column of the dataframe by column position:

In the below example 2nd ,4th 3rd and 1st column takes the position of 1 to 4 respectively

# Re order the column by position

df2 <- df1[,c(2,4,3,1)] 
df2

so the re ordered dataframe will be

Re order or Rearrange the column of dataframe in R 2

 

Re arrange the column of the dataframe by column name:

In the below we rearrange the column by column name

# Re order the column by name

df3 <- df1[,c("Grade_score","Mathematics1_score","Name","Science_score")]
df3

so the reordered dataframe will be

Re order or Rearrange the column of dataframe in R 3