在 R 中按月对行求和

Summing rows by month over years in R

所以我用这个 post 在 R 中按月汇总我的数据,但问题是,我的数据跨越多年。当前的解决方案会将 2018 年 1 月和 2019 年 1 月视为同一个月。有没有办法使用 aggregate() 和 month() 函数将它们按月分隔?还是我必须改变我的方法?

我的数据框如下所示:

           Day           Sales
    1      2019-02-04    219.12        
    2      2019-02-04    60.84
    3      2019-02-05    200.27
    4      2020-02-11    157.17
    5      2020-02-12    12.14

我的函数如下所示:

bymonth<-aggregate(sales~month(day,label=TRUE),data=total.orders.by.date,FUN=sum)

谢谢


这是一个使用 lubridate 库的例子

library(tidyverse)
library(lubridate)
result<-data.frame(Date=as.Date(c("18/12/2013", "12/12/2019", "15/8/2017", "09/08/2018"), format = "%d/%m/%Y"), Item = c(8002, 8004, 8001, 8002), result=c(21.45, 5.35, 35.99, 20.83)) 
result_2 <- result %>% 
  mutate(Month_only = month(Date)) %>% 
  group_by(Month_only) %>% 
  filter(between(Month_only, 1, 12)) %>% 
  summarise(total = sum(result, rm.na =TRUE))

#     Month_only total
#         <dbl> <dbl>
# 1          8  56.8
# 2         12  26.8

你可以试试这个:

library(tidyverse)
library(lubridate)
#Data
total.orders.by.date <- structure(list(Day = structure(c(17931, 17931, 17932, 18303, 
18304), class = "Date"), Sales = c(219.12, 60.84, 200.27, 157.17, 
12.14)), row.names = c("1", "2", "3", "4", "5"), class = "data.frame")

#Code
total.orders.by.date %>% mutate(Month=month(Day,label = T),Year=year(Day)) %>%
  group_by(Year,Month) %>% summarise(Sales=sum(Sales,na.rm=T))

输出:

# A tibble: 2 x 3
# Groups:   Year [2]
   Year Month Sales
  <dbl> <ord> <dbl>
1  2019 Feb    480.
2  2020 Feb    169.