每周按类别汇总数据框

时间:2018-08-15 15:50:10

标签: r group-by dplyr aggregate

我有按日期和类别分组的数据。

Date        Category  Revenue
2000-01-01  TV        1050.5
2000-01-01  DVD       500.2
2000-01-02  TV        750.4
2000-01-02  DVD       750.3
...         ...       ... 

我必须每周汇总此数据。对于每个类别,我都需要每周收入。这将是时间序列,因此,如果我理解正确,则小组必须成为一个功能。如何实现呢?

1 个答案:

答案 0 :(得分:2)

require(tidyverse)
df <- read.table(text='Date        Category  Revenue
2000-01-02  TV        1050.5
                 2000-01-02  DVD       500.2
                 2000-01-03  TV        750.4
                 2000-01-03  DVD       750.3', header = T)
df <- df %>% 
  mutate(week = lubridate::floor_date(as.Date(Date),'week')) %>% 
  group_by(week, Category) %>% 
  summarise(Revenue = sum(Revenue))