Here is an example of how I would calculate sales grouped by year and month. I leave the Date column as a date, I make columns to label each row with its month and year, and I group by those new columns to calculate the average sales. Is that the sort of thin you need to do?
library(lubridate)
#>
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#>
#> date, intersect, setdiff, union
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
#Invent Data
StartDate <- ymd("2020-01-01")
EndDate <- ymd("2021-08-31")
DF <- data.frame(Date = seq.Date(from = StartDate,to = EndDate,by=14),
Sales=runif(n=44,min=1000,max=5000))
head(DF)
#> Date Sales
#> 1 2020-01-01 4801.526
#> 2 2020-01-15 4575.294
#> 3 2020-01-29 4302.132
#> 4 2020-02-12 1727.589
#> 5 2020-02-26 3844.938
#> 6 2020-03-11 3539.066
#Label rows with month and year
DF <- DF %>% mutate(Month = month(Date), Year = year(Date))
head(DF)
#> Date Sales Month Year
#> 1 2020-01-01 4801.526 1 2020
#> 2 2020-01-15 4575.294 1 2020
#> 3 2020-01-29 4302.132 1 2020
#> 4 2020-02-12 1727.589 2 2020
#> 5 2020-02-26 3844.938 2 2020
#> 6 2020-03-11 3539.066 3 2020
#Calculate average sales for each year and month
STATS <- DF %>% group_by(Year,Month) %>%
summarize(Avg = mean(Sales))
#> `summarise()` has grouped output by 'Year'. You can override using the `.groups` argument.
STATS
#> # A tibble: 20 x 3
#> # Groups: Year [2]
#> Year Month Avg
#> <dbl> <dbl> <dbl>
#> 1 2020 1 4560.
#> 2 2020 2 2786.
#> 3 2020 3 3042.
#> 4 2020 4 4205.
#> 5 2020 5 2746.
#> 6 2020 6 3617.
#> 7 2020 7 2081.
#> 8 2020 8 3388.
#> 9 2020 9 2067.
#> 10 2020 10 3131.
#> 11 2020 11 2885.
#> 12 2020 12 3209.
#> 13 2021 1 3300.
#> 14 2021 2 3324.
#> 15 2021 3 3424.
#> 16 2021 4 3200.
#> 17 2021 5 3520.
#> 18 2021 6 3028.
#> 19 2021 7 1420.
#> 20 2021 8 4292.
Created on 2021-10-09 by the reprex package (v2.0.1)