将 top_n 的结果与“Other"组合起来dplyr 中的类别 [英] Combine result from top_n with an "Other" category in dplyr

查看:13
本文介绍了将 top_n 的结果与“Other"组合起来dplyr 中的类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框 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 的一个很好的例子.它在底层使用了 summarisesumarrange.

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"是原始数据中的factor,您可以将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 中的类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆