2017-01-03 59 views
3

我有一个包含列组的tibble,账户和持续时间,每行代表1个事件。我想创建一个很好的汇总表,其中包括组,账户,总计持续时间,计算价格以及最终总持续时间的组别比例。用dplyr计算多变量分组时变量的比例

重复的样品:

library(tidyverse) 
library(lubridate) 
tidy_data <- structure(list(group = c("Group 1", "Group 2", "Group 3", "Group 1", "Group 2", "Group 3", "Group 4", "Group 4", "Group 2"), account = c("Account 1", "Account 2","Account 3", "Account 1", "Account 2", "Account 3", "Account 4", "Account 4", "Account 2"), duration = structure(c(146.15, 181.416666666667, 96.9, 52.2833333333333, 99.4333333333333, 334.116666666667, 16.6333333333333, 11.5666666666667, 79.5666666666667), units = "mins", class = "difftime")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -9L), .Names = c("group","account", "duration")) 
hourPrice = 25 

总结1 - 正确地计算的比例,但不包括帐号

tidy_data %>% 
    group_by(group) %>% 
    summarise(total = sum(duration) %>% time_length(unit = "hour") %>% round(digits = 2), 
         price = (total*hourPrice) %>% round(digits = 0)) %>% 
    mutate(prop = (price/sum(price) * 100) %>% round(digits = 0)) 

# A tibble: 4 × 4 
    group total price prop 
    <chr> <dbl> <dbl> <dbl> 
1 Group 1 3.31 83 20 
2 Group 2 6.01 150 35 
3 Group 3 7.18 180 42 
4 Group 4 0.47 12  3 

摘要2 - 包括帐号,但无法计算比例正确

tidy_data %>% 
    group_by(group, account) %>% 
    summarise(total = sum(duration) %>% time_length(unit = "hour") %>% round(digits = 2), 
         price = (total*hourPrice) %>% round(digits = 0)) %>% 
    mutate(prop = (price/sum(price) * 100) %>% round(digits = 0)) 

#Source: local data frame [4 x 5] 
#Groups: group [4] 

    group account total price prop 
    <chr>  <chr> <dbl> <dbl> <dbl> 
1 Group 1 Account 1 3.31 83 100 
2 Group 2 Account 2 6.01 150 100 
3 Group 3 Account 3 7.18 180 100 
4 Group 4 Account 4 0.47 12 100 

我意识到问题是,由于这两个在第二种情况下,总结只能在一个组内进行。我考虑完成摘要1,然后将帐号重新加入表格,但在我看来,必须有更好的解决方案。

编辑:输出我想:

group account total price prop 
    <chr>  <chr> <dbl> <dbl> <dbl> 
1 Group 1 Account 1 3.31 83 20 
2 Group 2 Account 2 6.01 150 35 
3 Group 3 Account 3 7.18 180 42 
4 Group 4 Account 4 0.47 12  3 

回答

0

相反的summarise,我们使用mutate数据集中创建新列,然后slice每个“组”的第一行,计算“道具'并删除'持续时间'列

tidy_data %>% 
     group_by(group) %>% 
     mutate(total = sum(duration) %>% 
       time_length(unit = "hour") %>% 
       round(digits = 2), 
       price = (total*hourPrice) %>% 
       round(digits = 0)) %>% 
     slice(1L) %>% 
     ungroup() %>% 
     mutate(prop = (price/sum(price) * 100) %>% 
      round(digits = 0)) %>% 
     select(-duration)  
# A tibble: 4 × 5 
#  group account total price prop 
#  <chr>  <chr> <dbl> <dbl> <dbl> 
# 1 Group 1 Account 1 3.31 83 20 
# 2 Group 2 Account 2 6.01 150 35 
# 3 Group 3 Account 3 7.18 180 42 
# 4 Group 4 Account 4 0.47 12  3 
+1

这就是诀窍! :-)我不知道slice命令,起初对我来说并不直观,它会选择每个组的第一行,但我喜欢这个解决方案。 – emiltb