We often need to sort our rows or reorder the columns. We can do this using the functions in dplyr package. We’ll be using ‘iris’ dataset in this blog which is the built-in dataset in R. Let’s see the functions usage below.
- arrange()
arrange() function sort the rows based on columns where the first column will be the first one to be sorted then based on second column and so on.
#Sort rows based on Species in descending order & Sepal.Length in ascending order
iris%>%arrange(desc(Species), Sepal.Length)
2. arrange_all()
This functions sort all the data from left to right
#Sort all the data from left to right in descending order
iris%>%arrange_all(desc)
3. arrange_if()
arrange_if() sort the rows based on column criteria
#Based on numeric columns, sort the data in descending order
iris%>%arrange_if(is.numeric, desc)
4. arrange_at()
arrange_at() function sort the rows based on selected columns.
#Sort rows based on Species & columns starting with 'P' in descending order
iris %>%arrange_at(vars(Species, starts_with("P")), desc)
Select() function to reorder the columns
We can use select() function to reorder the columns.
#Reorder the columns starting from columns containing 'P' in the beginning and then the rest
iris %>%select(starts_with("P"), everything())
#Sort the columns alphabetically (Extract column names using current_vars() function)
iris %>%select(sort(current_vars()))
Thank you for reading 🙂
References: https://itsalocke.com/files/DataManipulationinR.pdf
Leave a Reply