多列汇总数据帧

时间:2020-01-23 10:30:14

标签: r dataframe

我想知道如何总结R中的更多列。 我有一个像这样的data.frame(df):

device  customer  message  count_today  count_yesterday
1       x          a        5              3
1       x          b        1              2
2       y          c        0              1
3       z          a        5              2
1       x          a        7              4

我想总结每个客户的邮件计数。 这是我希望得到的结果:

customer  count_today  count_yesterday
x          13            9
y          0             1
z          5             2

我尝试使用summary函数来获取count_today和count_yesterday的部分结果,但是似乎正在汇总每个设备的出现次数。

这是我尝试的代码:

df_today <- select(df, customer, count_today) %>%
  group_by(cutomer) %>%
    summarise(count_today=n()) %>%
      arrange(., customer)

df_yesterday <- select(df, customer, count_yesterday) %>%
  group_by(cutomer) %>%
    summarise(count_yesterday=n()) %>%
      arrange(., customer)

df_final <-merge(x = df_today, y = df_yesterday, by = "customer", all.x = TRUE, all.y = TRUE)

我所得到的就是这个:

customer  count_today  count_yesterday
x          3            3
y          1            1
z          1            1

可以请你帮我吗? 感谢您的任何建议。

1 个答案:

答案 0 :(得分:1)

通过用sum而不是n进行汇总,您将得到想要的结果。

library(dplyr)

df %>%
  group_by(customer) %>%
  summarise_at(c("count_today", "count_yesterday"), sum)

# A tibble: 3 x 3
  customer count_today count_yesterday
  <chr>          <int>           <int>
1 x                 13               9
2 y                  0               1
3 z                  5               2