Reorder or Rearrange the column of the dataframe in R, is accomplished either by column name or by column position. We will depict three different example on how to rearrange the column in R. Let’s see how to
- Rearrange the column of the dataframe by column name.
- Rearrange the column of the dataframe by column position.
- Rearrange or Reorder the column of the dataframe in R using Dplyr
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
Rearrange 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
Rearrange 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
Rearrange or Reorder the column of the dataframe using Dplyr :
Re order the column using select function with all the columns arranged in order of our choice.
# Reorder the columns of the dataframe library(dplyr) Mydata1 = select(df1,Grade_score,Science_score,Mathematics1_score,Name) Mydata1
so the resultant dataframe with all the column names rearranged will be