简体   繁体   English

按R中的过去日期(12个月)汇总

[英]aggregate by past dates (12 months) in R

I am trying to summarise/aggregate data by date. 我正在尝试按日期汇总/汇总数据。 For simplicity, I only need to do it for row 4 in the following data example. 为简单起见,在下面的数据示例中,我仅需要对第4行执行此操作。 For example, the date in row 4 is "2014-06-06" (June 2014), so I want to sum Price and Vat (by Group_ID) for all dates in the last 12 months ie between 2013-06-01 and 2014-05-31 (ie, sum of row 1,2,3,6). 例如,第4行中的日期为“ 2014-06-06”(2014年6月),因此我想对过去12个月(即2013-06-01至2014年)的所有日期的价格和增值税(按Group_ID)求和-05-31(即第1,2,3,6行的总和)。

 Date       Price    Vat    Group_ID
 2014-01-10   705000  5023.00   A      
 2014-05-11   580000  6786.00   A       
 2014-05-19   333000  1809.84   A    
 2014-06-06   213000  1875.00   A (need result for this row only)     
 2014-06-21   310000  1905.96   B    
 2013-06-30   280000  3227.00   A
 2014-06-22   280000  3227.00   B
 2014-06-16   280000  3227.00   B
 2014-06-15   280000  3227.00   B
 2013-05-18   280000  3227.00   A    

The expected result for row 4 would be: 第4行的预期结果将是:

Date         S_Price   S_Vat      Group_ID
2014-06-06   1898000  16845.84     A  

You could use lubridate and between to create groups with target dates and then summarise the data frame. 您可以使用lubridate和之间来创建具有目标日期的组,然后汇总数据框。 Here is my solution: 这是我的解决方案:

library(tidyverse)
library(lubridate)

df_2 <- df %>%
    mutate(target_date = case_when(
        between(Date,ymd("2013-06-01"),ymd("2014-05-31")) ~"2014-06-06",
        TRUE ~"0"
    )) %>%
    group_by(target_date, Group_ID) %>%
    summarise(S_price = sum(Price),
              S_Vat = sum(Vat)) %>%
    filter(target_date == "2014-06-06")

df_2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM