Open In App

Sort DataFrame by column name in R

Last Updated : 24 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sorting is the process of ordering items. It can be ascending order, descending order, alphabetical order, numerical order. To sort a DataFrame by column name in R programming, we can use various methods as discussed below. To get a better understanding of how to sort DataFrame by column name, let’s take some examples.

Example:

Let’s suppose we have the following dataset with column names as English alphabets and tuples are integer values. Now we want to sort the column by column name in alphabetical order. 

 

  Column Names          

R

o

w

s

Banana Orange Mango  Apple
1 6 2 4
6 2 4 2
5 3 4 3
5 7 0 9
6 4 3 7

After sorting DataFrame by column name it should look alike this:

            Sorted Column name

R

o

w

s

Apple Banana Mango Orange
4 6 2 1
2 2 4 6
3 3 4 5
9 7 0 5
7 4 3 6

Method 1: Using dplyr

dplyr is used to manipulate the DataFrame and names is used to set or get to the object name in R. To use dplyr, it needs to be installed explicitly.

Approach

  • Import library
  • Create data frame
  • Sort the DataFrame using sort function and pass the DataFrame name as an argument.

Syntax:

DataFrame %>% select(sort(names(DataFrame)))

  • Display sorted dataframe

Example:

R




#Sort DataFrame by column name in R
 
# Creating a dataset.
z <- c(1,6,5,5,6)
x <- c(6,2,3,7,4)
y <- c(2,4,4,0,3)
a <- c(4,2,3,9,7)
 
dataframe <- data.frame(Banana = z,Orange=x,Mango=y,Apple=a)
 
# install dplyr package
install.packages("dplyr")
 
# loading library
library("dplyr")
 
# sorting
dataframe %>% select(sort(names(dataframe)))
dataframe


Output:

Sorted DataFrame

Method 2: Using order

We can use the order function to sort the columns by column name.

Syntax:

order(names(dataframe))

Approach

  • Create dataframe
  • Pass the names of columns in order function
  • Save the sorted data
  • Display result

Program:

R




#Sort DataFrame by column name in R
 
# Creating a dataset.
z <- c(1,6,5,5,6)
x <- c(6,2,3,7,4)
y <- c(2,4,4,0,3)
a <- c(4,2,3,9,7)
 
dataframe <- data.frame(Banana = z,Orange=x,Mango=y,Apple=a)
 
# sorting
dataframe[order(names(dataframe))]


Output:

Sorted dataframe



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads