使用dplyr汇总数据,需要更聪明的方法

时间:2018-01-23 18:10:34

标签: r dplyr tidyverse

我有一个针对10个品牌的调查数据集,如下所示(我已经整理了数据):

# A tibble: 10 x 4
   InterviewStart      InterviewEnd        survay    response
   <dttm>              <dttm>              <chr>     <chr>
 1 2017-12-02 00:21:23 2017-12-02 00:29:36 Brnd1_QRA 1    
 2 2017-12-02 03:52:07 2017-12-02 04:00:37 Brnd1_QRA 0    
 3 2017-12-01 08:23:34 2017-12-01 08:30:37 Brnd1_QRA 0    
 4 2017-12-01 10:34:36 2017-12-01 10:40:48 Brnd1_QRA 1    
 5 2017-12-01 23:25:35 2017-12-01 23:30:28 Brnd1_QRA 1    
 6 2017-12-01 20:02:49 2017-12-01 20:12:02 Brnd1_QRA 0    
 7 2017-12-01 21:56:18 2017-12-01 22:04:48 Brnd1_QRA 0    
 8 2017-12-01 23:38:49 2017-12-01 23:40:07 Brnd1_QRA 1    
 9 2017-12-01 00:43:03 2017-12-01 00:52:50 Brnd1_QRA 0    
10 2017-12-01 00:20:09 2017-12-01 00:21:10 Brnd1_QRA 0

我想离散response col并计算每个响应的总和和平均值。我的代码看起来像这样:

  data_tidy %>% 
  mutate(response = if_else(response == 1, "Aware", "Not_Aware")) %>% 
  select(survay, response) %>% 
  filter(survay == "Brnd1_QRA") %>% 
  group_by(response) %>% 
  summarise( surveyee = n()) %>% 
  mutate ( total = sum(surveyee) , mean = surveyee / total)

得到这样的东西:

  response    surveyee total  mean
  <chr>        <int> <int> <dbl>
1 Aware          2553   4527 0.56
2 Not_Aware      1974   4527 0.44

我想知道,如果没有第二次变异,有没有更明智的方法呢?

1 个答案:

答案 0 :(得分:2)

Is there a reason that you are filtering out the other brands? It seems likely to lead to a lot of code duplication.

Instead, I would suggest summarising by group and using separate columns (instead of rows) for the counts of aware/not.

First, some reproducible data:

myData <-
  data_frame(
    survay = rep(LETTERS[1:3], each = 20)
    , response = sample(0:1, 60, TRUE)
  )

Then, the basic approach, which counts up each type of response (your code above suggests that values other than 0 may be possible for the "Not_aware" response, so I am sticking with your != 1 instead of using == 0), grabs the total, then calculates the proportion aware. If you really want the proportion unaware, you could add another column using the same structure.

myData %>%
  group_by(survay) %>%
  summarise(
    Aware = sum(response == 1)
    , `Not Aware` = sum(response != 1)
    , Total = n()
    , `Prop Aware` = Aware / Total
  )

returns

# A tibble: 3 x 5
  survay Aware `Not Aware` Total `Prop Aware`
  <chr>  <int>       <int> <int>        <dbl>
1 A          9          11    20        0.450
2 B         11           9    20        0.550
3 C         10          10    20        0.500