R Dplyr:按两个变量分组并计算外部组的行数

时间:2019-01-08 22:49:11

标签: r group-by dplyr

我有以下小标题,按Case.ID和工作日分组


    # A tibble: 10 x 4
    # Groups:   Case.ID [3]
        Case.ID weekday   count proportion
          <dbl> <chr>     <int>      <dbl>
     1 2771451. Friday        1   0.000992
     2 2771451. Monday        7   0.00694 
     3 2771451. Thursday      3   0.00298 
     4 2771451. Tuesday      20   0.0198  
     5 2771451. Wednesday    22   0.0218  
     6 2783345. Monday        9   0.00893 
     7 2783345. Thursday      1   0.000992
     8 2783345. Tuesday       1   0.000992
     9 2783345. Wednesday    40   0.0397  
    10 2846764. Friday       18   0.0179  

    > dput(a)
    structure(list(Case.ID = c(2771451, 2771451, 2771451, 2771451, 
    2771451, 2783345, 2783345, 2783345, 2783345, 2846764), weekday = c("Friday", 
    "Monday", "Thursday", "Tuesday", "Wednesday", "Monday", "Thursday", 
    "Tuesday", "Wednesday", "Friday"), count = c(1L, 7L, 3L, 20L, 
    22L, 9L, 1L, 1L, 40L, 18L), proportion = c(0.000992, 
    0.00694, 0.00298, 0.0198, 
    0.0218, 0.00893, 0.000992, 
    0.000992, 0.0397, 0.0179)), .Names = c("Case.ID", 
    "weekday", "count", "proportion"), row.names = c(NA, -10L), class = c("grouped_df", 
    "tbl_df", "tbl", "data.frame"), vars = "Case.ID", drop = TRUE, indices = list(
        0:4, 5:8, 9L), group_sizes = c(5L, 4L, 1L), biggest_group_size = 5L, labels = structure(list(
        Case.ID = c(2771451, 2783345, 2846764)), row.names = c(NA, 
    -3L), class = "data.frame", vars = "Case.ID", drop = TRUE, .Names = "Case.ID"))

目前,“比例”是用占总行数的百分比计算的(我知道这些数字是错误的,因为这只是我的小标题……),就像我以前使用的原始数据集一样:

group_by(Case.ID,weekday) %>% 
    summarise(count = n(),proportion = count / nrow(.))

我想基于每个Case.ID组的计数列的总和来计算比例。

例如,对于2771451案例,星期五,它应该为1 /(1 + 7 + 3 + 20 + 22)。

我希望使用dplyr解决方案...

1 个答案:

答案 0 :(得分:2)

那将是以下内容:

df %>% dplyr::group_by(Case.ID) %>% dplyr::mutate(proportion = count / sum(count))

请注意,我只是在Case.ID上分组,没有在使用summarise