I have a dat1 data frame
Country Count 1 AUS 1 2 NZ 2 3 NZ 1 4 USA 3 5 AUS 1 6 IND 2 7 AUS 4 8 USA 2 9 JPN 5 10 CN 2
First I want to summarize "Count" for "Country". Then, the top 3 totals for each country should be combined with an additional row of “Other”, which is the sum of countries that are not in the top three.
Thus, the expected result:
Country Count 1 AUS 6 2 JPN 5 3 USA 5 4 Others 7
I tried the code below but couldn’t figure out how to place the string “Others”.
dat1 %>% group_by(Country) %>% summarise(Count = sum(Count)) %>% arrange(desc(Count)) %>% top_n(3)
This code currently gives:
Country Count 1 AUS 6 2 JPN 5 3 USA 5
Any help would be greatly appreciated.
dat1 <- structure(list(Country = structure(c(1L, 5L, 5L, 6L, 1L, 3L, 1L, 6L, 4L, 2L), .Label = c("AUS", "CN", "IND", "JPN", "NZ", "USA"), class = "factor"), Count = c(1L, 2L, 1L, 3L, 1L, 2L, 4L, 2L, 5L, 2L)), .Names = c("Country", "Count"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))