【问题标题】:Dplyr: Summarise, mutate and rank within groupDplyr:在组内总结、变异和排名
【发布时间】:2016-07-22 08:16:28
【问题描述】:

当我对 mtcars 数据集执行以下查询时,我得到以下结果。

mtcars %>% 
   group_by(cyl,gear) %>% 
   summarise(total_cnt = n(), totalwt = sum(wt)) %>% 
   arrange(cyl, gear, desc(total_cnt), desc(totalwt)) %>% 
   mutate(rank = dense_rank(desc(total_cnt))) %>% 
   arrange(rank)

 cyl  gear total totalwt  rank
  <dbl> <dbl> <int>   <dbl> <int>
1     4     4     8  19.025     1
2     6     4     4  12.375     1
3     8     3    12  49.249     1
4     4     5     2   3.653     2
5     6     3     2   6.675     2
6     8     5     2   6.740     2
7     4     3     1   2.465     3
8     6     5     1   2.770     3

现在在每组(等级)中,我想根据totalwt 对观察结果进行子等级排序,因此最终输出应如下所示(每个等级组内totalwt 的降序排列)

cyl  gear total_cnt totalwt  rank    subrank
  <dbl> <dbl>     <int>   <dbl> <int>   <int>
1     4     4         8  19.025     1    2
2     6     4         4  12.375     1    3
3     8     3        12  49.249     1    1
4     4     5         2   3.653     2    3
5     6     3         2   6.675     2    2
6     8     5         2   6.740     2    1
7     4     3         1   2.465     3    2
8     6     5         1   2.770     3    1

然后最后是前 1,其中子排名 = 1 的每个排名,所以输出将是:

  cyl  gear total_cnt totalwt  rank    subrank
  <dbl> <dbl>     <int>   <dbl> <int>   <int>
3     8     3        12  49.249     1    1
6     8     5         2   6.740     2    1
8     6     5         1   2.770     3    1

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    如果 'mtcars1' 是从 OP 的代码中输出的,我们可以使用rank 在按 'rank' 分组后创建 'subrank'

    mtcars2 <- mtcars1 %>%
                   group_by(rank) %>%
                   mutate(subrank = rank(-totalwt))
    mtcars2
    #    cyl  gear total_cnt totalwt  rank subrank
    #   <dbl> <dbl>     <int>   <dbl> <int>   <dbl>
    #1     4     4         8  19.025     1       2
    #2     6     4         4  12.375     1       3
    #3     8     3        12  49.249     1       1
    #4     4     5         2   3.653     2       3
    #5     6     3         2   6.675     2       2
    #6     8     5         2   6.740     2       1
    #7     4     3         1   2.465     3       2
    #8     6     5         1   2.770     3       1
    

    然后,我们filter 'subrank' 为 1 的行

    mtcars2 %>% 
          filter(subrank ==1)
    #    cyl  gear total_cnt totalwt  rank subrank
    #   <dbl> <dbl>     <int>   <dbl> <int>   <dbl>
    #1     8     3        12  49.249     1       1
    #2     8     5         2   6.740     2       1
    #3     6     5         1   2.770     3       1
    

    【讨论】:

      猜你喜欢
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2016-04-30
      • 1970-01-01
      • 1970-01-01
      • 2017-12-30
      • 2017-10-05
      • 1970-01-01
      相关资源
      最近更新 更多