【问题标题】:R dplyr getting percentage after multiple groupby columnsR dplyr 在多个 groupby 列后获得百分比
【发布时间】:2018-07-10 13:27:05
【问题描述】:

我已经使用三列完成了一个组,现在我想获取每个组的百分比:

   GENDER      preference                           option num_users
   <fct>       <fct>                               <int>     <int>
 1 Female      Sweet                                   1       136
 2 Female      Sweet                                   2        28
 3 Female      Don't Know                              1        18
 4 Female      Don't Know                              2         2
 5 Female      Medium Spicy                            1        62
 6 Female      Medium Spicy                            2         6
 7 Female      Spicy                                   1        84
 8 Female      Spicy                                   2        20
 9 Female      Hot                                     1        35
10 Female      Hot                                     2         5
# ... with 17 more rows

当我只使用Gender 和Option 进行分组时,我设法使用了transmute,但在添加preference 之后transmute 不起作用。

这是我在组中没有preference 列的方法:

grouped_df <- df %>% 
group_by(GENDER, option) %>% 
summarize(num_users = n()) %>% 
spread(GENDER, num_users) %>% 
ungroup() %>% 
transmute(option_id = option, 
  female_percent = Female/(Female + Male), 
  male_percent = Male / (Female + Male)) %>% 
mutate(female_percent = round(100 * female_percent), 
  male_percent = round(100 * male_percent))

如何在上述方法中使用偏好?

【问题讨论】:

  • 能否提供reproducible格式的数据?
  • 如果您按gender 本身分组,您想找到gender 的百分比是多少?请添加当前结果和想要的结果。

标签: r dplyr tidyr


【解决方案1】:

我想这就是你想要的,我不得不从头开始创建一个数据框,因为你没有提供这样做的代码,但想法是一样的。

set.seed(1)

df <- data.frame(gender = rep(c("Male", "Female"), each = 10),
           preference = rep(c("Sweet", "Don't Know", "Medium Spicy", "Spicy", "Hot"), 2),
           option = rep(c(1, 2), 2),
           num_users = sample(1:150, 20))

df %>% 
  group_by(gender, option) %>% 
  mutate(perc = prop.table(num_users) * 100) %>%
  select(-num_users) %>% 
  spread(preference, perc)

# A tibble: 4 x 7
# Groups:   gender, option [4]
  gender option `Don't Know`   Hot `Medium Spicy` Spicy Sweet
  <fct>   <dbl>        <dbl> <dbl>          <dbl> <dbl> <dbl>
1 Female      1        22.8  24.7            33.6  12    6.82
2 Female      2         6.58 26.8            34.7  13.9 17.9 
3 Male        1        35.9   7.85           22.3  23.6 10.5 
4 Male        2        13.2   2.12           22.4  31.5 30.8 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-21
    • 1970-01-01
    • 2019-04-09
    • 2020-01-20
    • 2019-11-27
    • 1970-01-01
    • 2016-03-08
    • 2019-05-21
    相关资源
    最近更新 更多