Sort DataFrame by column name in R
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.
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: R o w s
Sorted Column name 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 t the object name in R. To use dplyr, it needs to be installed explicitly.
- Import library
- Create data frame
- Sort the DataFrame using sort function and pass the DataFrame name as an argument.
DataFrame %>% select(sort(names(DataFrame)))
- Display sorted dataframe
Method 2: Using order
We can use the order function to sort the columns by column name.
- Create dataframe
- Pass the names of columns in order function
- Save the sorted data
- Display result