/
market-modelling2.R
1370 lines (1133 loc) · 70.4 KB
/
market-modelling2.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#NOTE: Ctrl-F "YOURPATH" to find all paths you need to change to your own.
##################################################################
## Preparation ##
##################################################################
#clear workspace
rm(list = ls())
##:::::::::::::::::##
## Installations ##
##:::::::::::::::::##
# INSTALLATIONS ----
# Handy package that Installs, Updates and Loads
# packages from CRAN, Github & Bioconductor
# install.packages("librarian")
library("librarian")
#install & load packages with shelf function
librarian::shelf(RColorBrewer, lmtest, aTSA, ggplot2, ggcorrplot, dplyr, fastDummies,
car,corrplot,dplyr, vars, urca, mclust, tidyr, reshape2, ISOweek, lubridate, mice, tidyverse, VIM, quiet = TRUE)
##::::::::::
## Data ::
##::::::::::
# DATA ----
setwd("YOURPATH") #set working directory#
lemonade <- read.csv("YOURPATH", header = TRUE)
lemonade$Chain <- as.factor(lemonade$Chain)
lemonade$Brand <- as.factor(lemonade$Brand)
lemonade$Date <- ISOweek2date(sub("(wk) (\\d{2}) (\\d{2})","20\\3-W\\2-1", lemonade$Week))
lemonade$Quarter <- as.factor(quarter(lemonade$Date))
str(lemonade) #types of variables examined: correct.
summary(lemonade) #unitsales 741k!;128 NA's;
#missing values
sum(is.na(lemonade))
#check missed data in a specific attribute
summary.na<-lemonade %>% summarise_all(funs(sum(is.na(.))))
View(summary.na)
dim(summary.na)
#UnitSales, PricePU, PricePL, BasePricePU, BasePricePU - Each of the 4 variables have NAs.
#Visualize missing data
#percentage + histogram + pattern
aggr_plot <- aggr(lemonade, col=c('navyblue','red'),
numbers=TRUE,
sortVars=TRUE,
labels=names(data),
cex.axis=.7,
gap=3,
ylab=c("Histogram of Missing data","Pattern"))
# 1.make graphs of variables over time ----
# extract week num from time data
lemonade <- lemonade %>%
separate(Week, c('removed', 'week_num', 'year'), ' ') %>%
mutate(cleaned_wk = trimws((week_num),which='left',whitespace='0'))
lemonade$cleaned_wk <- as.numeric(unlist(lemonade$cleaned_wk))
# in order to generate graphs over time, reassign week num according to year no. with if else statements
attach(lemonade)
lemonade$week_yrs <- ifelse(year=='17',seq(1,52),
ifelse(year=='18',seq(53,104),
ifelse(year=='19',seq(105,156),
ifelse(year=='20',seq(157,208),NA))))
# create variable 'sales'
lemonade$sales <- UnitSales*PricePU
# create variables 'discountPU_raw' (raw price difference)
# and 'discountPU_perc' (percent discount)
lemonade$discount_raw <- BasePricePU - PricePU
lemonade$discount_perc <- ((BasePricePU - PricePU) / BasePricePU) * 100
#create ADJUSTED PROMOTION VARIABLES
str(which(lemonade$FeatDisp+lemonade$FeatOnly+lemonade$DispOnly > 100)) # just see how many rows there are (not used in function below)
#Create dummy which says 1 if the sum is more than 100 (used in the variable creation ifstatement)
lemonade$sum100 <- ifelse(lemonade$FeatDisp+lemonade$FeatOnly+lemonade$DispOnly > 100, 1, 0)
#Creating the adjusted promotion colums
lemonade$FeatOnly_Adjusted <- ifelse(lemonade$sum100 =='1',
((lemonade$FeatOnly / (lemonade$FeatDisp+lemonade$FeatOnly+lemonade$DispOnly))*100), lemonade$FeatOnly)
lemonade$DispOnly_Adjusted <- ifelse(lemonade$sum100 =='1',
((lemonade$DispOnly / (lemonade$FeatDisp+lemonade$FeatOnly+lemonade$DispOnly))*100), lemonade$DispOnly)
lemonade$FeatDisp_Adjusted <- ifelse(lemonade$sum100 =='1',
((lemonade$FeatDisp / (lemonade$FeatDisp+lemonade$FeatOnly+lemonade$DispOnly))*100), lemonade$FeatDisp)
# do some cleaning up
lemonade <- lemonade[,-c(3,4)]
lemonade <- relocate(lemonade, week_yrs, .after = Brand)
lemonade <- relocate(lemonade, sales, .after = UnitSales)
lemonade <- relocate(lemonade, cleaned_wk, .after = Brand)
lemonade <- relocate(lemonade, discount_raw, .after = BasePricePL)
lemonade <- relocate(lemonade, discount_perc, .after = discount_raw)
lemonade <- relocate(lemonade, sum100, .after = FeatDisp_Adjusted)
lemonade <- relocate(lemonade, FeatOnly_Adjusted, .after = FeatDisp)
lemonade <- relocate(lemonade, DispOnly_Adjusted, .after = FeatOnly_Adjusted)
lemonade <- relocate(lemonade, FeatDisp_Adjusted, .after = DispOnly_Adjusted)
#Gaining some general insights
#Total unit sales
plot(lemonade$UnitSales, xlab = "Observation", ylab = "Unit Sales", main = "Unit Sales",type = "o", pch = 20,col="dodgerblue")
#Identifying median and outliers
boxplot(lemonade$BasePricePU[lemonade$BasePricePU>0]~lemonade$Brand[lemonade$BasePricePU>0],col="firebrick1",ylab = "Prices (\u20AC)", main = "Prices per brand", xlab = NULL)
boxplot(lemonade$BasePricePU[lemonade$BasePricePU>0]~lemonade$Chain[lemonade$BasePricePU>0],col=c("dodgerblue", "orange", "firebrick2", "dodgerblue", "gold","yellowgreen", "grey") ,ylab = "Prices (\u20AC)", xlab = NULL, main = "Prices per chain" )
BrandNames <- levels(unique(lemonade$Brand))
ChainNames <- levels(unique(lemonade$Chain))
ChainColors <- c("dodgerblue", "orange", "firebrick2", "dodgerblue","gold","yellowgreen","grey")
names(ChainColors) <- c("Albert Heijn", "Coop", "Deen", "Hoogvliet", "Jumbo", "Plus", "TotalOnlineSales")
BoxPlotChainColors <- NULL
for (i in 1:length(ChainNames)) {
BoxPlotChainColors <- c(BoxPlotChainColors, rep(ChainColors[ChainNames[i]],length(BrandNames)))
}
op <- par(mar = c(8,4,4,2) + 0.1) ## default is c(5,4,4,2) + 0.1 Temporarily increase X-margin to allow for long brand names
boxplot(lemonade$BasePricePU[lemonade$BasePricePU>0]~lemonade$Brand[lemonade$BasePricePU>0] + lemonade$Chain[lemonade$BasePricePU>0],las=2,col=BoxPlotChainColors, main="Prices per chain per brand",ylab="Price (\u20AC)",names=rep(BrandNames,7),xlab = NULL)
StartText <- 4
for (i in 1:length(ChainNames)) {
text(StartText+(i-1)*6,3.2,ChainNames[i],col=ChainColors[ChainNames[i]])
}
op <- par(mar = c(5,4,4,2) + 0.1) ## set margins back to default, which is c(5,4,4,2) + 0.1
# make graphs of variables over time
# sales by channel; legend brand
lemonade %>%
filter(Chain=='Albert Heijn') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Albert Heijn') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Coop') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Coop') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Deen') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Deen') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Hoogvliet') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Hoogvliet') +
xlab("Week") + ylab("Unit Sales (\u20ac)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Jumbo') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Jumbo') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Plus') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Plus') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='TotalOnlineSales') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Brand)) +
ggtitle('Unit Sales per Brand Over Time\nChannel: Online (total)') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
# sales by brand; legend channel
lemonade %>%
filter(Brand=='EuroShopper') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Chain)) +
ggtitle('Unit Sales per Channel Over Time\nBrand: EuroShopper') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='KarvanCevitam') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Chain)) +
ggtitle('Sales per Channel Over Time\nBrand: Karavan Cevitam') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='PrivateLabel') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Chain)) +
ggtitle('Unit Sales per Channel Over Time\nBrand: Private Labels') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Raak') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Chain)) +
ggtitle('Unit Sales per Channel Over Time\nBrand: Raak') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Slimpie') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Chain)) +
ggtitle('Unit Sales per Channel Over Time\nBrand: Slimpie') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Teisseire') %>%
ggplot(aes(x=Date, y=UnitSales)) +
geom_line(aes(colour=Chain)) +
ggtitle('Unit Sales per Channel Over Time\nBrand: Teisseire') +
xlab("Week") + ylab("Unit Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
# discount (%) by channel; legend brand
lemonade %>%
filter(Chain=='Albert Heijn') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: Albert Heijn') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Coop') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: Coop') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Deen') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: Deen') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Hoogvliet') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: Hoogvliet') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Jumbo') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: Jumbo') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='Plus') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: Plus') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Chain=='TotalOnlineSales') %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Brand)) +
ggtitle('Discount (%) per Brand Over Time\nChannel: TotalOnlineSales') +
xlab("Week") + ylab("Discount (%)") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
# 2.1 building brand position map----
seg.summ <- function(data , groups) {aggregate(data , list(groups), function(x) mean(as.numeric(x), na.rm = TRUE))}
lemonade_bp <- seg.summ(lemonade[, c("UnitSales", "PricePU")], lemonade$Brand)
ggplot(data=lemonade_bp,
aes(x = UnitSales, y = PricePU, label = Group.1)) +
geom_hline(yintercept = 0, colour = "gray70") +
geom_vline(xintercept = 0, colour = "gray70") +
geom_text(aes(colour=Group.1),size = 6) +
ggtitle("Brand Maps - UnitSales X Price") +
theme(legend.position = "none") +
theme(axis.title = element_text(size=20))+
theme(plot.title = element_text(size=20))+
xlim(-50000,100000) #including negative value only to show the full label name in the chart for aesthetics purpose!
# 2.2 investigate frequency of promotion across different brands and supermarket formulas?----
# create dummies for each kind of promotion
lemonade$FeatOnlyD <- as.integer(ifelse(lemonade$FeatOnly>0,1,0))
lemonade$DispOnlyD <- as.integer(ifelse(lemonade$DispOnly>0,1,0))
lemonade$FeatDispD <- as.integer(ifelse(lemonade$FeatDisp>0,1,0))
# frequency of promotion across different brands
seg.summ <- function(data , groups) {aggregate(data , list(groups), function(x) sum(data.frame(x)))}
lemonade_promotion_fq <- seg.summ(lemonade[, c("FeatOnlyD", "DispOnlyD", "FeatDispD")], lemonade$Brand)
colnames(lemonade_promotion_fq)[1] <- 'Brand'
lemonade_promotion_fq <- melt(lemonade_promotion_fq, id = c("Brand"))
ggplot(data=lemonade_promotion_fq,
aes(x=reorder(lemonade_promotion_fq$variable,lemonade_promotion_fq$value,decreasing = TRUE),
y=lemonade_promotion_fq$value, fill=lemonade_promotion_fq$Brand)) +
ggtitle('Promotion Frequency per Brand') +
xlab("Promotion Type") + ylab("Total Promotions") + labs(fill = "Brand") +
geom_col(position = position_dodge())
# frequency of promotion across different supermarket formulas
seg.summ <- function(data , groups) {aggregate(data , list(groups), function(x) sum(data.frame(x)))}
lemonade_promotion_fq <- seg.summ(lemonade[, c("FeatOnlyD", "DispOnlyD", "FeatDispD")], lemonade$Chain)
colnames(lemonade_promotion_fq)[1] <- 'Chain'
lemonade_promotion_fq <- melt(lemonade_promotion_fq, id = c("Chain"))
ggplot(data=lemonade_promotion_fq,
aes(x=reorder(lemonade_promotion_fq$variable,lemonade_promotion_fq$value,decreasing = TRUE),
y=lemonade_promotion_fq$value, fill=lemonade_promotion_fq$Chain)) +
ggtitle('Promotion Frequency per Channel') +
xlab("Promotion Type") + ylab("Total Promotions") + labs(fill = "Channel") +
geom_col(position = position_dodge())
# depth of promotion across different brands
seg.summ <- function(data , groups) {aggregate(data , list(groups), function(x) mean(x,na.rm=TRUE))}
lemonade_promotion_depth <- seg.summ(lemonade[, c("discount_perc")], lemonade$Brand)
colnames(lemonade_promotion_depth)[1] <- 'Brand'
ggplot(data=lemonade_promotion_depth,
aes(x=reorder(lemonade_promotion_depth$Brand,lemonade_promotion_depth$x,decreasing = TRUE),
y=lemonade_promotion_depth$x, fill=lemonade_promotion_depth$Brand)) +
ggtitle('Promotion Depth per Brand') +
xlab("Brand") + ylab("Aggregated mean value of discount in %") + labs(fill = "Brand") +
geom_col(position = position_dodge())
# depth of promotion across different supermarket formulas
seg.summ <- function(data , groups) {aggregate(data , list(groups), function(x) mean(x,na.rm=TRUE))}
lemonade_promotion_depth <- seg.summ(lemonade[, c("discount_perc")], lemonade$Chain)
colnames(lemonade_promotion_depth)[1] <- 'Chain'
ggplot(data=lemonade_promotion_depth,
aes(x=reorder(lemonade_promotion_depth$Chain,lemonade_promotion_depth$x,decreasing = TRUE),
y=lemonade_promotion_depth$x, fill=lemonade_promotion_depth$Chain)) +
ggtitle('Promotion Depth per Chain') +
xlab("Brand") + ylab("Aggregated mean value of discount in %") + labs(fill = "Chain") +
geom_col(position = position_dodge())
# 3.(seasonal influences) ----
anova_quarter <- aov(UnitSales ~ Quarter, data = lemonade)
summary(anova_quarter)
# visualization for the seasonal influence
lemonadeRaak <- lemonade[lemonade$Brand == "Raak",] # make dataframe with only Raak at all chains
boxplot((lemonadeRaak$UnitSales[lemonadeRaak$UnitSales>0])/1000 ~ lemonadeRaak$Quarter[lemonadeRaak$UnitSales>0] + lemonadeRaak$Chain[lemonadeRaak$UnitSales>0],las=2,col="#0DBDC2", main="Raak UnitSales per chain per quarter",ylab="Unit sales (x 1000)",xlab = NULL)
# 4.simple linear regression to see the effect of price on sales----
ModelAllBrandsAllChains <- lm(UnitSales ~ PricePU, data = lemonade)
summary(ModelAllBrandsAllChains)
by(lemonade,lemonade[,c("Chain", "Brand")],function(x) summary(lm(UnitSales~PricePU,data = x)))
# Effect of Price (per brand)
by(lemonade,lemonade[,c("Brand")],function(x) summary(lm(UnitSales~PricePU,data = x)))
# Effect of Discount (per brand)
by(lemonade,lemonade[,c("Brand")],function(x) summary(lm(UnitSales~discount_perc,data = x)))
# Effect of Feature Promotion (per brand)
by(lemonade,lemonade[,c("Brand")],function(x) summary(lm(UnitSales~FeatOnly_Adjusted,data = x)))
# Effect of Display Promotion (per brand)
by(lemonade,lemonade[,c("Brand")],function(x) summary(lm(UnitSales~DispOnly_Adjusted,data = x)))
# Effect of F&D Promotion (per brand)
by(lemonade,lemonade[,c("Brand")],function(x) summary(lm(UnitSales~FeatDisp_Adjusted,data = x)))
# 5.more graph analysis on the selected brand Raak----
# help me to inspect data more easily...
# write.csv(lemonade,file="lemonade.csv")
lemonade %>%
filter(Brand=='Raak') %>%
ggplot(aes(x=Date, y=UnitSales/1000)) +
geom_line(aes(colour=Chain)) +
ggtitle('Unit Sales per Channel Over Time\nBrand: Raak') +
xlab("Week") + ylab("Unit Sales x 1000") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Raak') %>%
ggplot(aes(x=Date, y=sales/1000)) +
geom_line(aes(colour=Chain)) +
ggtitle('Sales per Channel Over Time\nBrand: Raak') +
xlab("Week") + ylab("Sales x 1000") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Raak') %>%
ggplot(aes(x=Date, y=PricePU)) +
geom_line(aes(colour=Chain)) +
ggtitle('PricePU per Channel Over Time\nBrand: Raak') +
xlab("Week") + ylab("PricePU") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Raak') %>%
ggplot(aes(x=Date, y=BasePricePU)) +
geom_line(aes(colour=Chain)) +
ggtitle('BasePricePU per Channel Over Time\nBrand: Raak') +
xlab("Week") + ylab("BasePricePU") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
lemonade %>%
filter(Brand=='Raak'& Chain=="Albert Heijn") %>%
ggplot(aes(x=Date, y=discount_perc)) +
geom_line(aes(colour=Chain)) +
ggtitle('Discount Percentage per Channel Over Time\nBrand: Raak') +
xlab("Week") + ylab("discount_perc") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
# Relational Plots
glimpse(lemonade[,c("UnitSales","PricePU","FeatOnly_Adjusted","DispOnly_Adjusted","FeatDisp_Adjusted","Quarter","discount_perc")])
# Correlation Matrix between key variables
lemonade.cor <- cor(lemonade[lemonade$Brand == "Raak",][,c("sales","PricePU","FeatOnly_Adjusted","DispOnly_Adjusted","FeatDisp_Adjusted","discount_perc")])
ggcorrplot(lemonade.cor,
hc.order = TRUE,
type = "lower",
lab = TRUE,
colors = brewer.pal(3,"RdBu"))
# Regression plots
#Feature
ggplot(subset(lemonade, Brand == "Raak"), aes(x = FeatOnly_Adjusted, y= sales ))+
geom_point()+
stat_smooth(method=lm) +
ggtitle('Feature Promotion effect on Sales \n Brand: Raak') +
xlab("Feature Promotion") + ylab("Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
#Display
ggplot(subset(lemonade, Brand == "Raak"), aes(x = DispOnly_Adjusted, y= sales ))+
geom_point()+
stat_smooth(method=lm) +
ggtitle('Display Promotion effect on Sales \n Brand: Raak') +
xlab("Display Promotion") + ylab("Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
#Feature & Display
ggplot(subset(lemonade, Brand == "Raak"), aes(x = FeatDisp_Adjusted, y= sales ))+
geom_point()+
stat_smooth(method=lm) +
ggtitle('Feature & Display Promotion effect on Sales \n Brand: Raak') +
xlab("F&D Promotion") + ylab("Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
#Discount
ggplot(subset(lemonade, Brand == "Raak"), aes(x = discount_perc, y= sales ))+
geom_point()+
stat_smooth(method=lm) +
ggtitle('Discount effect on Sales \n Brand: Raak') +
xlab("Discount") + ylab("Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
#Price (per unit)
ggplot(subset(lemonade, Brand == "Raak"), aes(x = PricePU, y= sales ))+
geom_point()+
stat_smooth(method=lm) +
ggtitle('Price (per unit) effect on Sales \n Brand: Raak') +
xlab("Price") + ylab("Sales") +
theme(plot.title = element_text(color="black", size=14, face="bold", hjust = 0.5))
# Dominant promotion influence
# Create Promotion dominance groups
# : 1-Feature dominant, 2-Display dominant, 3-Combination dominant (if there is no clear dominance then NA, so that it's excluded from the analysis)
lemonade$PromoDominance <- ifelse(lemonade$FeatOnly_Adjusted > lemonade$DispOnly_Adjusted & lemonade$FeatOnly_Adjusted > lemonade$FeatDisp_Adjusted,1,
ifelse(lemonade$DispOnly_Adjusted > lemonade$FeatOnly_Adjusted & lemonade$DispOnly_Adjusted > lemonade$FeatDisp_Adjusted,2,
ifelse(lemonade$FeatDisp_Adjusted > lemonade$FeatOnly_Adjusted & lemonade$FeatDisp_Adjusted > lemonade$DispOnly_Adjusted,3,NA)))
anova_promo <- aov(UnitSales ~ as.factor(PromoDominance), data = lemonade)
summary(anova_promo)
TukeyHSD(anova_promo)
# model corrected - by Elias Date: 01/06/2022----
Lemonade <- lemonade
# remove unnecessary stuff from the environment
rm(aggr_plot,anova_promo,anova_quarter,le_endo,le_exo,lemonade_bp,lemonade_est,lemonade_promotion_depth,lemonade_promotion_fq,lemonade.cor,lemonadeRaak,ModelAllBrandsAllChains,op,summary.na)
rm(BoxPlotChainColors,ChainColors,i,StartText,seg.summ)
rm(lemonade)
# create smooth version of BasePricePU
#Check for inconsistiencies:
Lemonade$Promotion <- Lemonade$BasePricePU - Lemonade$PricePU
percentagefalse <- (sum(Lemonade$Promotion < 0, na.rm=TRUE)/nrow(Lemonade))*100
Lemonade$BasePricePU_Smooth <- rep(0,nrow(Lemonade)) #create a new variable in the data frame - a smoothed version of BasePricePU - initially filled up with zeros
#Loop over chains and brands: within this loop, loess regression is used to create a smoothed version of BasePricePU
for(ch in ChainNames){
for(br in BrandNames){
loess_temp <- loess(Lemonade$BasePricePU[Lemonade$Chain==ch & Lemonade$Brand==br]~c(1:length(Lemonade$BasePricePU[Lemonade$Chain==ch & Lemonade$Brand==br])),span=0.10)
if (length(Lemonade$BasePricePU_Smooth[Lemonade$Chain==ch & Lemonade$Brand==br]) != length(loess_temp$fitted)) {
fill_up <- c(loess_temp$fitted,rep(NA,length(Lemonade$BasePricePU_Smooth[Lemonade$Chain==ch & Lemonade$Brand==br])-length(loess_temp$fitted)))
Lemonade$BasePricePU_Smooth[Lemonade$Chain==ch & Lemonade$Brand==br] <- fill_up
} else {
Lemonade$BasePricePU_Smooth[Lemonade$Chain==ch & Lemonade$Brand==br] <- loess_temp$fitted
}
}
}
#Now that smoothing is done, replace any remaining smoothed BasePricePU values by PricePU values if they are lower than PricePU
Lemonade$BasePricePU_Smooth <- ifelse(Lemonade$BasePricePU_Smooth > Lemonade$PricePU, Lemonade$BasePricePU_Smooth, Lemonade$PricePU)
#Now check again if there are inconsistencies
Lemonade$Promotion <- Lemonade$BasePricePU_Smooth - Lemonade$PricePU
percentagefalse <- (sum(Lemonade$Promotion < 0, na.rm=TRUE)/nrow(Lemonade))*100 # now no inconsistencies anymore
#Just a visual check how it looks like for one brand-chain combination:
plot(Lemonade$PricePU[Lemonade$Chain=="Jumbo" & Lemonade$Brand=="Raak"],type="l")
lines(Lemonade$BasePricePU_Smooth[Lemonade$Chain=="Jumbo" & Lemonade$Brand=="Raak"],type="l",col="red")
# combine covid data
# Download COVID data from the web ----
Covid_cases <- read.csv("https://github.com/CSSEGISandData/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv")
# Data cleaning ----
## Only focus on data from the Netherlands ----
Covid_cases_Reduced <- Covid_cases[Covid_cases$Country.Region == "Netherlands",]
## Only focus on data from the main country ----
Covid_cases_Reduced_Further <- Covid_cases_Reduced[Covid_cases_Reduced$Province.State == "",]
## Transpose the dataframe and exclude the first four entries ----
Covid_cases_df <- data.frame(t(Covid_cases_Reduced_Further[,-c(1:4)]))
## Extract a date variable from the row names ----
Covid_cases_df$Date <- as.Date(row.names(Covid_cases_df),"X%m.%d.%y")
## Rename focal variable ----
names(Covid_cases_df)[names(Covid_cases_df)=="X201"] <- "CovidCases"
## Make a plot of the focal variable ----
plot(Covid_cases_df$Date,Covid_cases_df$CovidCases,type="l")
## Create a new variable, consisting of new cases ----
Covid_cases_df$NewCovidCases <- c(NA,diff(Covid_cases_df$CovidCases,1))
## Make a plot of the new variable ----
plot(Covid_cases_df$Date,Covid_cases_df$NewCovidCases,type="l")
## Replace one very extreme outlier ----
Covid_cases_df$NewCovidCases[Covid_cases_df$NewCovidCases > 150000] <- max(Covid_cases_df$NewCovidCases[Covid_cases_df$NewCovidCases < 150000],na.rm = TRUE)
## Make a plot of the new variable again - does this look better? ----
plot(Covid_cases_df$Date,Covid_cases_df$NewCovidCases,type="l")
## Add a week variable ----
library(lubridate)
Covid_cases_df$Week <- week(Covid_cases_df$Date)
Covid_cases_df$Year <- year(Covid_cases_df$Date)
## Calculate weekly averages ----
Years <- unique(Covid_cases_df$Year)
Weeks <- unique(Covid_cases_df$Week)
for (iYear in Years) {
for (iWeek in Weeks) {
Covid_cases_df$WeekAverage[Covid_cases_df$Year == iYear & Covid_cases_df$Week == iWeek] <- mean(Covid_cases_df$NewCovidCases[Covid_cases_df$Year == iYear & Covid_cases_df$Week == iWeek],na.rm = TRUE)
}
}
## Make a plot to check whether we created the weekly average correctly
plot(Covid_cases_df$Date,Covid_cases_df$NewCovidCases,type="l")
lines(Covid_cases_df$Date,Covid_cases_df$WeekAverage,type="l", col="Red")
# Clean up after getting external data ----
rm(Covid_cases,Covid_cases_Reduced,Covid_cases_Reduced_Further,iWeek,Weeks)
# Combine lemonade data and covid data ----
Covid_cases_df <- subset(Covid_cases_df,select = c("Week","Year","WeekAverage"))
Covid_cases_df <- Covid_cases_df %>% distinct(Year, Week, .keep_all = TRUE)
Lemonade$year <- year(Lemonade$Date)
Lemonade_extended <- data.frame()
for(ch in ChainNames){
for(br in BrandNames){
Lemonade_ch_br <- merge(subset(Lemonade[Lemonade$Chain==ch & Lemonade$Brand==br, ]),Covid_cases_df,by.x = c("year","cleaned_wk"),by.y = c("Year","Week"),all.x = TRUE)
Lemonade_extended <- rbind(Lemonade_extended, Lemonade_ch_br)
}
}
# combine extended data and weather data----
WeatherDF <- read.csv("etmgeg_280.csv", header = TRUE)
WeatherDF$Date <- as.Date(as.character(WeatherDF$YYYYMMDD),"%Y%m%d")
WeatherDF$Week <- ISOweek(WeatherDF$Date)
TempAvg <- aggregate(TG/10~Week, FUN=mean, data=WeatherDF, na.rm=TRUE)
UniqueDates <- unique(Lemonade_extended$Date)
Lemonade_extended$Temp <- rep(0,nrow(Lemonade_extended))
for (i in 1:length(UniqueDates)) {
Lemonade_extended$Temp[Lemonade_extended$Date==UniqueDates[i]] <- TempAvg[ISOweek2date(paste(TempAvg$Week,"1",sep="-")) == UniqueDates[i],"TG/10"]
}
rm(WeatherDF)
# include dynamic effect - partial adjustment
# first, select subset of Raak
LemonadeRaak <- subset(Lemonade_extended[Lemonade_extended$Brand == "Raak", ])
# create variable lag of unitsales
LemonadeRaak$UnitSalesLag <- c(NA,LemonadeRaak$UnitSales[1:nrow(LemonadeRaak)-1])
LemonadeRaak$UnitSalesLag[LemonadeRaak$year == "2017" & LemonadeRaak$cleaned_wk == "1"] <- NA
# add competitors price
LemonadeRaak$PricePUPL <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$PricePUSlimpie <- rep(0,nrow(LemonadeRaak))
Dates <- unique(LemonadeRaak$Date)
Chains <- unique(LemonadeRaak$Chain)
for (i in Dates) {
for (j in Chains) {
LemonadeRaak$PricePUPL[LemonadeRaak$Chain == j & LemonadeRaak$Date == i] <- Lemonade$PricePU[Lemonade$Brand == "PrivateLabel" & Lemonade$Chain == j & Lemonade$Date == i]
LemonadeRaak$PricePUSlimpie[LemonadeRaak$Chain == j & LemonadeRaak$Date == i] <- Lemonade$PricePU[Lemonade$Brand == "Slimpie" & Lemonade$Chain == j & Lemonade$Date == i]
}
}
# create price index = price per unit/base price
LemonadeRaak$PriceIndex <- LemonadeRaak$PricePU/LemonadeRaak$BasePricePU_Smooth
#Building model----
#replace na with 0 in week average covid cases to keep degree of freedom
LemonadeRaak$WeekAverage[is.na(LemonadeRaak$WeekAverage)] <- 0
#unit by unit; unpooled
R2s <- data.frame(Chains) #Make the dataframe
for (i in Chains) { #loop over chains
MultiplicativeTemp <- lm(log(UnitSales) ~ log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak[LemonadeRaak$Chain==i,])
#This object changes for every value of i, and is not accessible outside of the loop
message("Output for ",i,":",sep="") #Writes this sentence in red to the console window
print(summary(MultiplicativeTemp)) #Prints the output to the screen
R2s$R2[which(Chains==i)] <- summary(MultiplicativeTemp)$r.squared
print(summary(aov(MultiplicativeTemp)))
#Stores the R2-value in the right row of the R2 variable in the data frame R2s
}
#total residual=4.374+4.665+9.1+6.193+1.842+9.051+8.729 !!!
print(R2s) #the R2 values are now accessible outside of the loop
#Pooled version of the model:
PooledModel <- lm(log(UnitSales) ~ log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak)
summary(PooledModel)
summary(aov(PooledModel))
#Partially pooled version of the model:
#First create dummies for the chains:
LemonadeRaak$D_AH <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_Jumbo <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_Plus <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_Coop <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_Deen <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_HV <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_TOS <- rep(0,nrow(LemonadeRaak))
LemonadeRaak$D_AH[LemonadeRaak$Chain=="Albert Heijn"] <- 1
LemonadeRaak$D_Jumbo[LemonadeRaak$Chain=="Jumbo"] <- 1
LemonadeRaak$D_Plus[LemonadeRaak$Chain=="Plus"] <- 1
LemonadeRaak$D_Coop[LemonadeRaak$Chain=="Coop"] <- 1
LemonadeRaak$D_Deen[LemonadeRaak$Chain=="Deen"] <- 1
LemonadeRaak$D_HV[LemonadeRaak$Chain=="Hoogvliet"] <- 1
LemonadeRaak$D_TOS[LemonadeRaak$Chain=="TotalOnlineSales"] <- 1
#Option 1: estimate model without intercept
PartiallyPooledModelTemp1 <- lm(log(UnitSales) ~ -1 + D_AH + D_Jumbo + D_Plus + D_Coop + D_Deen + D_HV + D_TOS +
log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak)
summary(PartiallyPooledModelTemp1)
#Option 2: estimate model with intercept
PartiallyPooledModelTemp2 <- lm(log(UnitSales) ~ D_AH + D_Jumbo + D_Plus + D_Coop + D_Deen + D_HV + D_TOS +
log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak)
summary(PartiallyPooledModelTemp2)
summary(aov(PartiallyPooledModelTemp2))
partially_pooled_sum_sq <- summary(aov(PartiallyPooledModelTemp2))[1][[1]][[2]][[17]] #69.8
pooled_sum_sq <- summary(aov(PooledModel))[1][[1]][[2]][[11]] #170.1
unit_by_unit_sum_sq <- 4.374+4.665+9.1+6.193+1.842+9.051+8.729 #43.954
# Please use a part of the data for estimation, and save a part for validation
LemonadeRaak_Calibrate <- LemonadeRaak[LemonadeRaak$Date < "2020-08-01",]
LemonadeRaak_Validate <- LemonadeRaak[LemonadeRaak$Date >= "2020-08-01",]
length(unique(LemonadeRaak_Calibrate$Date))
length(unique(LemonadeRaak_Validate$Date))
#performing the chow test----
#degree of freedom
#df_pooled = 7*207-11=1438
#df_unpooled = 7*(207-11)=1372 <---------- added up instead: 1378 = 196(AH)+196(Coop)+198(Deen)+196(Hoogvliet)+198(Jumbo)+196(Plus)+198(Online)
#df_partially_pooled = 7*207-17=1432
F_UnitbyUnit_P<- (
(pooled_sum_sq-unit_by_unit_sum_sq)/(1438-1372))/(
unit_by_unit_sum_sq/1372)
F_UnitbyUnit_P
#when F(66,1372), p-value = 0, fully pooled is not allowed
F_partiallyP_P <- (
(partially_pooled_sum_sq-unit_by_unit_sum_sq)/(1432-1372))/(
unit_by_unit_sum_sq/1372)
F_partiallyP_P
#when F(60,1372), p-value = 0 partially pooled is not allowed
#Therefore, we choose not to pool!
#performing the chow test (UPDATED - pls check it out just in case and delete this text) ----
#degree of freedom
#df_pooled = 7*207-11=1438
#df_unpooled = 7*(207-11)=1372 <---------- added up instead: 1378 = 196(AH)+196(Coop)+198(Deen)+196(Hoogvliet)+198(Jumbo)+196(Plus)+198(Online)
#df_partially_pooled = 7*207-17=1432
F_UnitbyUnit_P_update<- (
(pooled_sum_sq-unit_by_unit_sum_sq)/(1438-1378))/(
unit_by_unit_sum_sq/1378)
F_UnitbyUnit_P_update # = 65.89476
#when F(60,1378), p-value = 0, fully pooled is not allowed
F_partiallyP_P_update <- (
(partially_pooled_sum_sq-unit_by_unit_sum_sq)/(1432-1378))/(
unit_by_unit_sum_sq/1378)
F_partiallyP_P_update # = 14.99258
#when F(54,1378), p-value = 0 partially pooled is not allowed
#Therefore, we choose not to pool!
# vif test----
MultiplicativeAH <- lm(log(UnitSales) ~ log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain=="Albert Heijn",])
vif(MultiplicativeAH)
summary(MultiplicativeAH)
# log(BasePricePU_Smooth) log(PriceIndex) log(PricePUSlimpie)
# 1.215898 5.087799 1.130562
# log(PricePUPL) FeatOnly_Adjusted DispOnly_Adjusted
# 1.116053 17.354348 1.235906
# FeatDisp_Adjusted log(UnitSalesLag) log(Temp + 273)
# 11.547643 1.071903 1.095113
# WeekAverage
# 1.154179
MultiplicativePlus <- lm(log(UnitSales) ~ log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain=="Plus",])
vif(MultiplicativePlus)
# log(BasePricePU_Smooth) log(PriceIndex) log(PricePUSlimpie)
# 1.341361 4.061166 1.065802
# log(PricePUPL) FeatOnly_Adjusted DispOnly_Adjusted
# 1.285438 7.901394 1.671563
# FeatDisp_Adjusted log(UnitSalesLag) log(Temp + 273)
# 9.516049 1.691277 1.153694
# WeekAverage
# 1.192421
MultiplicativeCoop <- lm(log(UnitSales) ~ log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain=="Coop",])
vif(MultiplicativeCoop)
# log(BasePricePU_Smooth) log(PriceIndex) log(PricePUSlimpie)
# 1.261248 10.474991 1.024517
# log(PricePUPL) FeatOnly_Adjusted DispOnly_Adjusted
# 1.342303 8.520145 1.207626
# FeatDisp_Adjusted log(UnitSalesLag) log(Temp + 273)
# 1.873290 1.409149 1.466902
# WeekAverage
# 1.220419
MultiplicativeHoogvliet <- lm(log(UnitSales) ~ log(BasePricePU_Smooth)+log(PriceIndex)+log(PricePUSlimpie)+log(PricePUPL)
+ FeatOnly_Adjusted + DispOnly_Adjusted + FeatDisp_Adjusted + log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain=="Hoogvliet",])
vif(MultiplicativeHoogvliet)
summary(MultiplicativeHoogvliet)
# log(BasePricePU_Smooth) log(PriceIndex) log(PricePUSlimpie)
# 1.691111 5.503598 1.293660
# log(PricePUPL) FeatOnly_Adjusted DispOnly_Adjusted
# 1.402924 1.992625 1.173843
# FeatDisp_Adjusted log(UnitSalesLag) log(Temp + 273)
# 4.401795 1.089811 1.164649
# WeekAverage
# 1.201136
# other 3 chains (excluded Jumbo, Deen and TOS, since they are missing data wrt F, D and FD) got multi-collinearity issue as well...
# CONCLUSION: We will solve the multicollinearity for the Hoogvliet chain and continue with it because it has the best VIF values overall.
# solve multi-collinearity: Hoogvliet ----
# We recode the Feat/Disp/FeatDisp variables and Price Index into new combined variables
# which signify the presence of both price and advertising promotion based on index
LemonadeRaak_Calibrate$PriceIndex # we already have our price index variable
#CUT-OFF LOGIC: to determine cut off value we look at boxplots and histograms
# BOXPLOT (F, D and F&D)
# Conclusion: if we look at where the majority of outliers start:
# for F it is around 8, for D around 2, for F&D around 41 => the cut off value we will use is 17
boxplot(LemonadeRaak_Calibrate[c("FeatOnly_Adjusted", "DispOnly_Adjusted", "FeatDisp_Adjusted")],
main = "Boxplots of 3 Promotion types",
at = c(1,2,3),
names = c("F Only", "D Only", "F&D"),
las = 1,
col = c("red","blue", "green"),
border = c("red","blue", "green"),
horizontal = FALSE,
notch = TRUE
)
# BOXPLOT (PriceIndex)
# Conclusion: we choose 0.766
hist(LemonadeRaak_Calibrate[c("PriceIndex")],
main="Feature Only Promotion Histogram",
col="darkmagenta",
freq=TRUE
)
#create cutoff variables for easy change if needed
promocutoff1 <- 17
pricecutoff1 <- 0.766
#recode price and promotion variables
# variable meaning:
# pf1: price index if there is feature only support (>17), otherwise 1
# pd1: price index if there is display only support (>17), otherwise 1
# pfd1: price index if there is feature & display support (>17), otherwise 1
# pwo1: price index if display only, feature only AND f&d support is (<=17), otherwise 1
# fwo1: feature only support, but no price cut (> 0.761), otherwise 0
# dwo1: display only support, but no price cut (> 0.761), otherwise 0
# fdwo1: f&d support, but no price cut (> 0.761), otherwise 0
#1: create and populate variables (which we replace in step 2 based on the cutoff)
LemonadeRaak_Calibrate$pf1 <- rep(1,nrow(LemonadeRaak_Calibrate))
LemonadeRaak_Calibrate$pd1 <- rep(1,nrow(LemonadeRaak_Calibrate))
LemonadeRaak_Calibrate$pfd1 <- rep(1,nrow(LemonadeRaak_Calibrate))
LemonadeRaak_Calibrate$pwo1 <- rep(1,nrow(LemonadeRaak_Calibrate))
LemonadeRaak_Calibrate$fwo1 <- rep(0,nrow(LemonadeRaak_Calibrate))
LemonadeRaak_Calibrate$dwo1 <- rep(0,nrow(LemonadeRaak_Calibrate))
LemonadeRaak_Calibrate$fdwo1 <- rep(0,nrow(LemonadeRaak_Calibrate))
#2: replace based on the logic of the cutoff value
LemonadeRaak_Calibrate$pf1[LemonadeRaak_Calibrate$FeatOnly_Adjusted > promocutoff1] <- LemonadeRaak_Calibrate$PriceIndex[LemonadeRaak_Calibrate$FeatOnly_Adjusted > promocutoff1]
LemonadeRaak_Calibrate$pd1[LemonadeRaak_Calibrate$DispOnly_Adjusted > promocutoff1] <- LemonadeRaak_Calibrate$PriceIndex[LemonadeRaak_Calibrate$DispOnly_Adjusted > promocutoff1]
LemonadeRaak_Calibrate$pfd1[LemonadeRaak_Calibrate$FeatDisp_Adjusted > promocutoff1] <- LemonadeRaak_Calibrate$PriceIndex[LemonadeRaak_Calibrate$FeatDisp_Adjusted > promocutoff1]
LemonadeRaak_Calibrate$pwo1[LemonadeRaak_Calibrate$FeatOnly_Adjusted <= promocutoff1 & LemonadeRaak_Calibrate$DispOnly_Adjusted <= promocutoff1 & LemonadeRaak_Calibrate$FeatDisp_Adjusted <= promocutoff1] <- LemonadeRaak_Calibrate$PriceIndex[LemonadeRaak_Calibrate$FeatOnly_Adjusted <= promocutoff1 & LemonadeRaak_Calibrate$DispOnly_Adjusted <= promocutoff1 & LemonadeRaak_Calibrate$FeatDisp_Adjusted <= promocutoff1]
LemonadeRaak_Calibrate$fwo1[LemonadeRaak_Calibrate$PriceIndex > pricecutoff1] <- LemonadeRaak_Calibrate$FeatOnly_Adjusted[LemonadeRaak_Calibrate$PriceIndex > pricecutoff1]
LemonadeRaak_Calibrate$dwo1[LemonadeRaak_Calibrate$PriceIndex > pricecutoff1] <- LemonadeRaak_Calibrate$DispOnly_Adjusted[LemonadeRaak_Calibrate$PriceIndex > pricecutoff1]
LemonadeRaak_Calibrate$fdwo1[LemonadeRaak_Calibrate$PriceIndex > pricecutoff1] <- LemonadeRaak_Calibrate$FeatDisp_Adjusted[LemonadeRaak_Calibrate$PriceIndex > pricecutoff1]
summary(LemonadeRaak_Calibrate[c("pf1","pd1","pfd1","pwo1","fwo1","dwo1","fdwo1")])
# pf1 pd1 pfd1 pwo1
# Min. :0.5169 Min. :0.6906 Min. :0.5176 Min. :0.6696
# 1st Qu.:1.0000 1st Qu.:1.0000 1st Qu.:1.0000 1st Qu.:0.9933
# Median :1.0000 Median :1.0000 Median :1.0000 Median :0.9995
# Mean :0.9856 Mean :0.9990 Mean :0.9914 Mean :0.9901
# 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.:1.0000 3rd Qu.:1.0000
# Max. :1.0000 Max. :1.0000 Max. :1.0000 Max. :1.0000
# fwo1 dwo1 fdwo1
# Min. : 0.000 Min. : 0.0000 Min. : 0.0000
# 1st Qu.: 0.000 1st Qu.: 0.0000 1st Qu.: 0.0000
# Median : 0.000 Median : 0.0000 Median : 0.0000
# Mean : 1.274 Mean : 0.7898 Mean : 0.9627
# 3rd Qu.: 0.000 3rd Qu.: 0.0000 3rd Qu.: 0.0000
# Max. :100.000 Max. :89.0000 Max. :73.9837
library(Hmisc)
rcorr(as.matrix(LemonadeRaak_Calibrate[c("pf1","pd1","pfd1","pwo1","fwo1","dwo1","fdwo1")]))
# pf1 pd1 pfd1 pwo1 fwo1 dwo1 fdwo1
# pf1 0.0000 0.0000 0.0039 0.0000 0.4351 0.0000
# pd1 0.0000 0.0000 0.3996 0.3521 0.0000 0.2673
# pfd1 0.0000 0.0000 0.0236 0.0000 0.9514 0.0000
# pwo1 0.0039 0.3996 0.0236 0.2744 0.0010 0.1018
# fwo1 0.0000 0.3521 0.0000 0.2744 0.6104 0.0000
# dwo1 0.4351 0.0000 0.9514 0.0010 0.6104 0.1320
# fdwo1 0.0000 0.2673 0.0000 0.1018 0.0000 0.1320
# HOOGVLIET
# Recoded model: Hoogvliet (removed old promotion and pricing variables + added new variables)
MultiplicativeHoogvliet_Recoded <- lm(log(UnitSales) ~ log(PricePUSlimpie)+log(PricePUPL)
+log(pf1)+log(pd1)+log(pfd1)+log(pwo1)+fwo1+dwo1+fdwo1
+ log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet", ])
vif(MultiplicativeHoogvliet_Recoded) # All VIF's are less than 5!
# log(PricePUSlimpie) log(PricePUPL) log(pf1) log(pd1)
# 1.185285 1.245755 4.963173 1.195184
# log(pfd1) log(pwo1) fwo1 dwo1
# 4.959370 1.094106 2.250392 1.173885
# fdwo1 log(UnitSalesLag) log(Temp + 273) WeekAverage
# 2.573918 1.115350 1.104925 1.159633
# Next we will build a recoded REDUCED model based on
# which variables may not have enough observations (5 observation rule of thumb)
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("pf1")] < 1) #17 observations
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("pd1")] < 1) #2 observations <- too few observations
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("pfd1")] < 1) #16 observations
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("pwo1")] < 1) #53 observations
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("fwo1")] > 0) #11 observations
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("dwo1")] > 0) #5 observations
sum(LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet",c("fdwo1")] > 0) #10 observations
# Recoded REDUCED model: Hoogvliet (removed new variables that didn't have enough observations for the chain)
MultiplicativeHoogvliet_Recoded.REDUCED <- lm(log(UnitSales) ~ log(PricePUSlimpie)+log(PricePUPL)
+log(pf1)+log(pfd1)+log(pwo1)+fwo1+dwo1+fdwo1
+ log(UnitSalesLag) + log(Temp+273) + WeekAverage,
data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet", ])
vif(MultiplicativeHoogvliet_Recoded.REDUCED)
# log(PricePUSlimpie) log(PricePUPL) log(pf1) log(pfd1)
# 1.183987 1.241649 4.932409 4.917970
# log(pwo1) fwo1 dwo1 fdwo1
# 1.092554 2.249794 1.113537 2.537682
# log(UnitSalesLag) log(Temp + 273) WeekAverage
# 1.110788 1.085707 1.158645
# Conclusion and 2 reasons
# All VIFs are within reasonable values for marketing variables (1)
# furthermore, as we are building a predictive model it is also reasonable to not exclude pf1 and pfd1 (2)
summary(MultiplicativeHoogvliet_Recoded.REDUCED)
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) -1.099e+01 3.978e+00 -2.764 0.006331 **
# log(PricePUSlimpie) 3.279e-02 1.569e-01 0.209 0.834717
# log(PricePUPL) 6.345e-01 2.423e-01 2.618 0.009617 **
# log(pf1) -1.898e+00 3.760e-01 -5.048 1.12e-06 ***
# log(pfd1) -1.395e+00 3.757e-01 -3.714 0.000275 ***
# log(pwo1) 1.512e+00 1.632e+00 0.926 0.355600
# fwo1 -3.469e-04 1.788e-03 -0.194 0.846348
# dwo1 -5.102e-03 7.034e-03 -0.725 0.469231
# fdwo1 7.545e-03 1.715e-03 4.399 1.89e-05 ***
# log(UnitSalesLag) 1.621e-01 3.783e-02 4.285 3.02e-05 ***
# log(Temp + 273) 3.231e+00 7.082e-01 4.561 9.56e-06 ***
# WeekAverage 2.712e-04 9.023e-05 3.006 0.003042 **
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 0.1899 on 174 degrees of freedom
# (1 observation deleted due to missingness)
# Multiple R-squared: 0.7755, Adjusted R-squared: 0.7613
# F-statistic: 54.63 on 11 and 174 DF, p-value: < 2.2e-16
# Heteroscedasticity: Hoogvliet ----
# VISUAL TEST: seems there are no Heteroscedasticity issues
df.heteroscedasticity.visual <- LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet", ]
is.na(df.heteroscedasticity.visual$UnitSalesLag) #NA in row 1
df.heteroscedasticity.visual <- df.heteroscedasticity.visual[-c(1),] #removed the NA in UnitSalesLag
df.heteroscedasticity.visual$residuals <- MultiplicativeHoogvliet_Recoded.REDUCED$residuals
ggplot(data = df.heteroscedasticity.visual, aes(y = residuals, x = week_yrs)) + geom_point(col = 'blue') + geom_abline(slope = 0)
# FORMAL TEST - Goldfield-Quandt: insignificant => Heteroscedasticity is not present
#https://www.statology.org/goldfeld-quandt-test-in-r/
# model: The linear regression model created by the lm() command.
# order.by: The predictor variable(s) in the model.
# data: The name of the dataset.
# fraction*: The number of central observations to remove from the dataset. Typically we choose to remove around 20% of the total observations.
gqtest(MultiplicativeHoogvliet_Recoded.REDUCED, order.by = ~log(PricePUSlimpie)+log(PricePUPL)+log(pf1)+log(pfd1)+log(pwo1)+fwo1+dwo1+fdwo1+log(UnitSalesLag)+log(Temp+273)+WeekAverage, data = LemonadeRaak_Calibrate[LemonadeRaak_Calibrate$Chain == "Hoogvliet", ], fraction = 36)
# GQ = 0.38192, df1 = 63, df2 = 63, p-value = 0.9999
# alternative hypothesis: variance increases from segment 1 to 2
# Autocorrelation: Hoogvliet ----
dwtest(MultiplicativeHoogvliet_Recoded.REDUCED)
# DW = 1.6873, p-value = 0.007732