Sort a Data Frame by Column in Ascending, Descending Order

R Tutorial – We shall learn to sort a data frame by column in ascending order and descending order with example R scripts using R with function and R order function.

Sort a Data Frame by Column

A data frame is a set of equal length objects.

Let us take an example Data frame as shown in the following :

The data frame has three columns : names, age, salary

We may sort these three columns in ascending or descending order.

 

Sort in Ascending order

Syntax

dataframe_name[with(dataframe_name, order(column_name)), ]

Example R Script

 

Sort in Descending order

Syntax

dataframe_name[with(dataframe_name, order(column_name)), ]

Please observe the ‘-‘ negative sign before the column_name to sort in descending order

Example R Script

Note : Descending order is not applicable for Character Datatypes. Observe lines (5,6) with a warning message.

Conclusion :

In this R Tutorial, we have learnt to sort a data frame by column in ascending and descending order.