问题描述
我有一个数据框 dat1
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
首先,我想对每个国家。然后,应将每个国家/地区的前3个总计数与其他其他行合并,该行不属于前3个国家/地区的总和。
First I want to sum "Count" per "Country". Then the top 3 total counts per country should be combined with an additional row "Others", which is the sum of countries which are not part of top 3.
因此,结果将是:
Country Count
1 AUS 6
2 JPN 5
3 USA 5
4 Others 7
我尝试了以下代码,但无法弄清楚如何放置其他行。
I have tried the below code, but could not figure out how to place the "Others" row.
dat1 %>%
group_by(Country) %>%
summarise(Count = sum(Count)) %>%
arrange(desc(Count)) %>%
top_n(3)
此代码当前提供:
Country Count
1 AUS 6
2 JPN 5
3 USA 5
任何帮助将不胜感激。
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"))
推荐答案
而不是 top_n
,对于便利功能 tally
,这似乎是一个很好的案例。它在引擎盖下使用 summary
, sum
和 arrange
。
Instead of top_n
, this seems like a good case for the convenience function tally
. It uses summarise
, sum
and arrange
under the hood.
然后使用 factor
创建其他类别。使用 levels
参数将其他设置为最后一个级别。然后,其他将放置在表格的最后位置(以及结果的任何后续绘图中)。
Then use factor
to create an "Other" category. Use the levels
argument to set "Other" as the last level. "Other" will then will be placed last in the table (and in any subsequent plot of the result).
如果国家/地区是因数
在原始数据中,您可以将 Country [1:3]
换成 as.character
。
If "Country" is factor
in your original data, you may wrap Country[1:3]
in as.character
.
group_by(df, Country) %>%
tally(Count, sort = TRUE) %>%
group_by(Country = factor(c(Country[1:3], rep("Other", n() - 3)),
levels = c(Country[1:3], "Other"))) %>%
tally(n)
# Country n
# (fctr) (int)
#1 AUS 6
#2 JPN 5
#3 USA 5
#4 Other 7
这篇关于将top_n的结果与“ Other”组合dplyr中的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!