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. 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).
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:
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. 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.