order() within order()

I need my data sorted two ways, and I don't know how to do the second without the first. Fairly new, so apologies if this is quite simple! Here's my head() table and the code I used to sort:

Malaria2 <- Malaria[order(Malaria$COUNTRY..DISPLAY.),]
head(Malaria2)

I've gotten everything sorted alphabetically by country, which is perfect. But now I need to order by year within country. There are four years for each country: 2000, 2005, 2010, and 2013. So I need all the Algerias together in order of year, followed by all the Angolas together in order of year, etc. How do I order by YEAR..CODE. within the ordering I already have of COUNTRY..DISPLAY.?

Here are two ways to sort the data frame. The dplyr package used in the second method has many very handy functions for manipulating data frame.

DAT <- data.frame(Country = c("R", "A", "E", "R", "E", "A", "E", "R", "A"),
                  Year = c(2010, 2010, 2010, 2015, 2015, 2015, 2004, 2004, 2004))
DAT
#>   Country Year
#> 1       R 2010
#> 2       A 2010
#> 3       E 2010
#> 4       R 2015
#> 5       E 2015
#> 6       A 2015
#> 7       E 2004
#> 8       R 2004
#> 9       A 2004
DAT[order(DAT$Country, DAT$Year),]
#>   Country Year
#> 9       A 2004
#> 2       A 2010
#> 6       A 2015
#> 7       E 2004
#> 3       E 2010
#> 5       E 2015
#> 8       R 2004
#> 1       R 2010
#> 4       R 2015
library(dplyr)
arrange(DAT, Country, Year)
#>   Country Year
#> 1       A 2004
#> 2       A 2010
#> 3       A 2015
#> 4       E 2004
#> 5       E 2010
#> 6       E 2015
#> 7       R 2004
#> 8       R 2010
#> 9       R 2015

Created on 2020-04-19 by the reprex package (v0.3.0)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.