如何使用R中的日期变量查找每月销售额?

销售分析需要找到每月的销售平均值,总数,范围以及通常的标准偏差。FMCG(快速消费品)公司最需要这样做,因为它们希望跟踪每天和每月的销售额。如果我们有每日销售数据,那么我们需要在R数据框中创建数月的另一列以查找每月销售,这可以借助strftime和聚合函数来完成。

示例

请看以下数据帧-

date<-c("2020/05/05","2020/05/05","2020/05/06","2020/06/10","2020/06/25",
+ "2020/06/25","2020/04/15","2020/05/25","2020/03/02","2020/02/25",
+ "2020/03/12","2020/02/21","2020/03/04","2020/04/21","2020/05/24",
+ "2020/02/17","2020/06/07","2020/04/08","2020/01/25","2020/01/04",
+ "2020/05/20","2020/01/24","2020/04/01")
sales<-c(17,25,14,19,21,24,26,28,18,25,26,18,19,25,20,17,10,18,26,27,21,24,18)
df<-data.frame(date,sales)
df

输出结果

   date sales
1 2020/05/05 17
2 2020/05/05 25
3 2020/05/06 14
4 2020/06/10 19
5 2020/06/25 21
6 2020/06/25 24
7 2020/04/15 26
8 2020/05/25 28
9 2020/03/02 18
10 2020/02/25 25
11 2020/03/12 26
12 2020/02/21 18
13 2020/03/04 19
14 2020/04/21 25
15 2020/05/24 20
16 2020/02/17 17
17 2020/06/07 10
18 2020/04/08 18
19 2020/01/25 26
20 2020/01/04 27
21 2020/05/20 21
22 2020/01/24 24
23 2020/04/01 18
m.date<-strftime(df$date,"%m")
Monthly_Sales_Mean<-aggregate(df$sales~m.date,FUN=mean)
Monthly_Sales_Mean
m.date df$sales
1 01 25.66667
2 02 20.00000
3 03 21.00000
4 04 21.75000
5 05 20.83333
6 06 18.50000
Monthly_Sales_Total<-aggregate(df$sales~m.date,FUN=sum)
Monthly_Sales_Total
m.date df$sales
1 01 77
2 02 60
3 03 63
4 04 87
5 05 125
6 06 74
Monthly_Sales_Range<-aggregate(df$sales~m.date,FUN=range)
Monthly_Sales_Range
m.date df$sales.1 df$sales.2
1 01 24 27
2 02 17 25
3 03 18 26
4 04 18 26
5 05 14 28
6 06 10 24
Monthly_Sales_SD<-aggregate(df$sales~m.date,FUN=sd)
Monthly_Sales_SD
m.date df$sales
1 01 1.527525
2 02 4.358899
3 03 4.358899
4 04 4.349329
5 05 5.115336
6 06 6.027714
猜你喜欢