I have data base containing Date, GEO, VALUE. I would like to first sort by Date, then by GEO and finally create a rank by descending VALUE.
Here is my df1, if there are any NAs which should be ranked as the last.
My output should be
structure(list(Date = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("01/01/2020",
"01/01/2021"), class = "factor"), GEO = structure(c(1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("Barrie",
"Toronto"), class = "factor"), NAICS = structure(c(14L, 17L,
8L, 10L, 14L, 17L, 8L, 10L, 14L, 17L, 12L, 6L, 14L, 17L, 12L,
6L), .Label = c("Accomd. & food serv.", "Agriculture", "Bus., build.,& other supp. services",
"Construction", "Educational services", "Fin., Insur., Real est., Rental, & lease",
"Forest.,Fish.,Mining.,Quar.,Oil & Gas", "Health care & Social Assis",
"Info., culture & rec.", "Manufacturing", "Other services (except pub. admin)",
"Prof., Sci.,and Tech. Serv", "Public administration", "Total",
"Transp. & warehousing", "Utilities", "Wholesale and retail trade"
), class = "factor"), VALUE = c(114.5, 17.6, 15.1, 14.4, 117.6,
17.1, NA, NA, 3393.4, 520.5, 443.9, 393.4, 3221.8, 486.2,
414.2, 400.5), rank = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L,
3L, 4L, 1L, 2L, 3L, 4L)), class = "data.frame", row.names = c(NA,
-16L))
My code doesn't quite work as it is not sorting by the Date, then GEO, then VALUE.
df1 %>%
arrange(GEO, desc(VALUE)) %>%
group_by(GEO) %>%
mutate(rank = row_number()) -> df1