13  Sorting with arrange()


author: Юрій Клебан


Before start load packages

library(dplyr) # for demos
#install.packages("gapminder")
library(gapminder)  # load package and dataset

arrange(.data, …) function order rows by values of a column or columns (low to high)You can use with desc() to order from high to low.

For example, we need to select top 10 countries in 2002 by lifeExp variable.

data2002 <- gapminder |>  
                filter(year == 2002) |>
                top_n(10, lifeExp) # select top 10 by lifeExp value
data2002
A tibble: 10 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
Australia Oceania 2002 80.370 19546792 30687.75
Canada Americas 2002 79.770 31902268 33328.97
Hong Kong, China Asia 2002 81.495 6762476 30209.02
Iceland Europe 2002 80.500 288030 31163.20
Israel Asia 2002 79.696 6029529 21905.60
Italy Europe 2002 80.240 57926999 27968.10
Japan Asia 2002 82.000 127065841 28604.59
Spain Europe 2002 79.780 40152517 24835.47
Sweden Europe 2002 80.040 8954175 29341.63
Switzerland Europe 2002 80.620 7361757 34480.96
# sort by pop
t <- data2002 |> arrange(pop) # you can use 1 or more sorting params like arrange(pop, year)
head(t)
A tibble: 6 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
Iceland Europe 2002 80.500 288030 31163.20
Israel Asia 2002 79.696 6029529 21905.60
Hong Kong, China Asia 2002 81.495 6762476 30209.02
Switzerland Europe 2002 80.620 7361757 34480.96
Sweden Europe 2002 80.040 8954175 29341.63
Australia Oceania 2002 80.370 19546792 30687.75
# sort by pop descending
t <- data2002 |> arrange(desc(pop))
head(t)
A tibble: 6 × 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
Japan Asia 2002 82.00 127065841 28604.59
Italy Europe 2002 80.24 57926999 27968.10
Spain Europe 2002 79.78 40152517 24835.47
Canada Americas 2002 79.77 31902268 33328.97
Australia Oceania 2002 80.37 19546792 30687.75
Sweden Europe 2002 80.04 8954175 29341.63

13.1 Refences

  1. dplyr: A Grammar of Data Manipulation on https://cran.r-project.org/.
  2. Data Transformation with splyr::cheat sheet.
  3. DPLYR TUTORIAL : DATA MANIPULATION (50 EXAMPLES) by Deepanshu Bhalla.
  4. Dplyr Intro by Stat 545. 6.R Dplyr Tutorial: Data Manipulation(Join) & Cleaning(Spread). Introduction to Data Analysis
  5. Loan Default Prediction. Beginners data set for financial analytics Kaggle