【问题标题】:R - group by and summarise categorial vars (top 2 with count)R - 分组和总结分类变量(前 2 个计数)
【发布时间】:2021-03-26 03:05:05
【问题描述】:

我需要按字段 A 对 data.frame 进行分组并汇总分类变量 B,并保留其前 2 个值和相应的计数。 B 有重复值。

示例数据:

## double to have duplicate values
mtcars2 <- rbind(mtcars, mtcars)

希望的代码示例(虽然我知道它并不简单):

mtcars2 %>% 
  group_by(gear) %>% 
  summarise(
    n = n(),
    disp_top1 = top(disp,1),
    disp_top1_n = top_count(cat1,1),
    disp_top2 = top(disp,2),
    disp_top2_n = top_count(cat1,2)
  )

结果会是这样的

   gear    nr disp_top1 disp_top1_n disp_top2 disp_top2_n
  <dbl> <int>     <dbl>       <int>     <dbl>       <int>
1     3    30      472            2       460           2
2     4    24      168.           4       160           4
3     5    10      351            2       301           2

感谢您的帮助!

【问题讨论】:

  • 请在您的问题中添加一个最小的可重现示例作为代码。你说的top1和top2是什么意思?去掉top1后,top1是mode,top2是mode吗?
  • 感谢@Dharman 和 Holzben。很抱歉没有发布可重现的代码和测试数据,新手错误 =)。我使用 mtcars 编辑了问题。我尝试了 Dharman 解决方案,对于 2+ 重复的 disp 值不起作用,所以我做了一些调整,现在它可以工作了。代码如下。想知道是否有更短更快的方法,因为我需要汇总 200 多个分类变量,超过 2 亿条记录。
  • @AnilGoyal,感谢您的提示!问题已编辑。还注册了我到目前为止的解决方案。

标签: r dplyr aggregate categorical-data summarize


【解决方案1】:

由于没有测试数据,我只能提供mtcars 数据集的示意图

mtcars %>% group_by(gear) %>% 
  mutate(position = rank(disp)) %>% 
  summarise(nr = n(),
            top_value_1 = disp[position == 1],
            top_value_2 = disp[position == 2],
            top_value_3 = disp[position == 3],
            top_value_nr_occurance_top_1 = sum(disp[position == 1] == disp),
            top_value_nr_occurance_top_2 = sum(disp[position == 2] == disp),
            top_value_nr_occurance_top_3 = sum(disp[position == 3] == disp))

在您的示例中,gear 将是 keydisp 将是 cat1

【讨论】:

    【解决方案2】:

    到目前为止回答(使用 mtcars 作为数据集),感谢 @holzben 和 @Dharman。

    ## double the data to get duplicate disp values
    mtcars2 <- rbind(mtcars, mtcars)
    
    ## summarising
    mtcars2 %>% group_by(gear) %>% 
      mutate(position = dense_rank(-disp)) %>% 
      summarise(
        nr = n(),
        top_value_1 = head(disp[position == 1],1),
        top_value_2 = head(disp[position == 2],1),
        top_value_1_nr = sum(top_value_1 == disp),
        top_value_2_nr = sum(top_value_2 == disp)
      )
    

    结果:

    `summarise()` ungrouping output (override with `.groups` argument)
    # A tibble: 3 x 6
       gear    nr top_value_1 top_value_2 top_value_1_nr top_value_2_nr
      <dbl> <int>       <dbl>       <dbl>          <int>          <int>
    1     3    30        472          460              2              2
    2     4    24        168.         160              4              4
    3     5    10        351          301              2              2
    

    【讨论】:

      猜你喜欢
      • 2020-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多