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

Using dplyr to summarize data , need a smarter way

我有如下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

我想知道,有没有更聪明的方法可以做到这一点而无需第二次变异?

您是否有理由过滤掉其他品牌?这似乎很可能导致大量代码重复。

相反,我建议按组汇总并使用单独的列(而不是行)来计算 aware/not.

的计数

首先,一些可重现的数据:

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

然后,计算每种类型响应的基本方法(您上面的代码表明 "Not_aware" 响应可能有 0 以外的值,所以我坚持使用您的!= 1 而不是使用 == 0),获取总数,然后计算比例。如果你真的不想知道比例,你可以使用相同的结构添加另一列。

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