13 Sorting with arrange()
author: Юрій Клебан
Before start load packages
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
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)
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 |
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
- dplyr: A Grammar of Data Manipulation on https://cran.r-project.org/.
- Data Transformation with splyr::cheat sheet.
- DPLYR TUTORIAL : DATA MANIPULATION (50 EXAMPLES) by Deepanshu Bhalla.
- Dplyr Intro by Stat 545. 6.R Dplyr Tutorial: Data Manipulation(Join) & Cleaning(Spread). Introduction to Data Analysis
- Loan Default Prediction. Beginners data set for financial analytics Kaggle