Sorting
Sort dataframes using arrange()
from dplyr
:
airquality %>%
arrange(Ozone) %>%
head
Ozone Solar.R Wind Temp Month Day
1 1 8 9.7 59 5 21
2 4 25 9.7 61 5 23
3 6 78 18.4 57 5 18
4 7 NA 6.9 74 5 11
5 7 48 14.3 80 7 15
6 7 49 10.3 69 9 24
By default sorting is ascending, but you can use a minus sign to reverse this:
airquality %>%
arrange(-Ozone) %>%
head
Ozone Solar.R Wind Temp Month Day
1 168 238 3.4 81 8 25
2 135 269 4.1 84 7 1
3 122 255 4.0 89 8 7
4 118 225 2.3 94 8 29
5 115 223 5.7 79 5 30
6 110 207 8.0 90 8 9
You can sort on multiple columns too, but the order of the variables makes a difference. This:
airquality %>%
select(Month, Ozone) %>%
arrange(Month, -Ozone) %>%
head
Month Ozone
1 5 115
2 5 45
3 5 41
4 5 37
5 5 36
6 5 34
Is different to this:
airquality %>%
select(Month, Ozone) %>%
arrange(-Ozone, Month) %>%
head
Month Ozone
1 8 168
2 7 135
3 8 122
4 8 118
5 5 115
6 8 110