Reverse the column order of the dataframe in R

To reverse the column order of the dataframe in R, we use order function. Let’s see how to reverse the order of the dataframe by column wise with an example.

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

Reverse the column order of the dataframe in R 1

 

Invert the column order in R – Reverse the column order of the dataframe:

Inverting the column order in R is done using order() and ncol() function as shown below.

## invert the column order in R

df2=df1[,order(ncol(df1):1)]
df2

So the resultant dataframe will be in inverted column order

Reverse the column order of the dataframe in R 2

 

Reverse the column order of the dataframe in R - image previous-small-11-1 on http://www.datasciencemadesimple.com                                                                                                                Reverse the column order of the dataframe in R - image next_small-11-1 on http://www.datasciencemadesimple.com