Given a dataframe df as follows:
df <- structure(list(city = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("bj", "sh"
), class = "factor"), district = structure(c(1L, 1L, 1L, 1L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L), .Label = c("cy", 
"hd", "hp", "pd"), class = "factor"), value = c(5L, 6L, 3L, 4L, 
2L, 4L, 5L, 2L, 5L, 7L, 8L, 8L, 9L, 9L, 6L, 3L, 2L)), class = "data.frame", row.names = c(NA, 
-17L))
I need to groupby city and district, then sort value column in descending way, and take top 2 for each groups.
The expected result will like this:
city district value
bj  cy  6       
bj  cy  5       
bj  hd  5       
bj  hd  4       
sh  hp  8       
sh  hp  8       
sh  pd  9       
sh  pd  9   
How could I do that in R? Thanks.
 
     
    