-
Notifications
You must be signed in to change notification settings - Fork 1
/
exploring_online_retail_transactions.qmd
2161 lines (1561 loc) · 52.2 KB
/
exploring_online_retail_transactions.qmd
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
---
title: "Exploring the Online Retail Transaction Data"
author: "Mick Cooney <[email protected]>"
date: "Last updated: `r format(Sys.time(), '%B %d, %Y')`"
editor: source
execute:
message: false
warning: false
error: false
format:
html:
light: superhero
dark: darkly
anchor-sections: true
embed-resources: true
number-sections: true
smooth-scroll: true
toc: true
toc-depth: 3
toc-location: left
code-fold: true
code-summary: "Show code"
---
```{r import_libraries}
#| echo: FALSE
#| message: FALSE
library(conflicted)
library(tidyverse)
library(scales)
library(cowplot)
library(magrittr)
library(rlang)
library(purrr)
library(furrr)
library(vctrs)
library(fs)
library(glue)
library(rsyslog)
library(forcats)
library(snakecase)
library(DataExplorer)
library(lubridate)
library(evir)
library(DT)
library(tidyquant)
library(directlabels)
source("lib_utils.R")
source("lib_btyd.R")
conflict_lst <- resolve_conflicts(
c("magrittr", "rlang", "dplyr", "readr", "purrr", "ggplot2", "MASS",
"fitdistrplus")
)
options(
width = 80L,
warn = 1,
mc.cores = parallel::detectCores()
)
theme_set(theme_cowplot())
set.seed(42)
open_syslog("exploring_online_retail_transactions")
plan(multisession)
```
```{r custom_functions}
#| echo: FALSE
### Checks if variable is a date/time
is_date <- function(x)
x |> inherits(c("POSIXt", "POSIXct", "POSIXlt", "Date", "hms"))
### Returns the category of data type passed to it
categorise_datatype <- function(x) {
if (all(are_na(x))) return("na")
if (is_date(x)) "datetime"
else if (!is_null(attributes(x)) ||
all(is_character(x))) "discrete"
else if (all(is_logical(x))) "logical"
else "continuous"
}
### create_coltype_list() splits columns into various types
create_coltype_list <- function(data_tbl) {
coltypes <- data_tbl |> map_chr(categorise_datatype)
cat_types <- coltypes |> unique() |> sort()
split_lst <- cat_types |> map(~ coltypes[coltypes %in% .x] |> names())
names(split_lst) <- coltypes |> unique() |> sort()
coltype_lst <- list(
split = split_lst,
columns = coltypes
)
return(coltype_lst)
}
```
This workbook was created using the "dataexpks" template:
https://github.com/DublinLearningGroup/dataexpks
# Introduction
This workbook performs the basic data exploration of the dataset.
```{r set_exploration_params}
#| echo: true
dataexp_level_exclusion_threshold <- 100
dataexp_cat_level_count <- 40
dataexp_hist_bins_count <- 50
```
# Load Data
First we load the dataset as well as some support datasets.
```{r load_dataset}
#| echo: true
syslog(
glue("Setting up data"),
level = "INFO"
)
rawdata_tbl <- read_rds("data/rawdata_online_retail_tbl.rds")
rawdata_tbl |> glimpse()
```
## Perform Quick Data Cleaning
Some of the dates provided in the dataset are in an irregular format.
```{r clean_names}
#| echo: true
data_tbl <- rawdata_tbl %>% set_colnames(names(.) |> to_snake_case()) #
data_tbl |> glimpse()
```
```{r}
#| echo: FALSE
#knitr::knit_exit()
```
## Create Derived Variables
We now create derived features useful for modelling. These values are
new variables calculated from existing variables in the data.
```{r construct_derived_values}
#| echo: true
data_tbl <- data_tbl |>
rename(invoice_id = invoice) |>
mutate(
row_id = sprintf("ROW%07d", 1:n()),
.before = 1
) |>
mutate(
stock_code_upr = stock_code |> str_to_upper(),
cancellation = str_detect(invoice_id, "^C"),
invoice_dttm = invoice_date,
invoice_date = invoice_date |> as.Date(),
invoice_month = format(invoice_dttm, "%B") |> fct_reorder(invoice_dttm |> format("%m") |> as.numeric()),
invoice_dow = format(invoice_dttm, "%A") |> fct_reorder(invoice_dttm |> format("%u") |> as.numeric()),
invoice_dom = format(invoice_dttm, "%d"),
invoice_hour = format(invoice_dttm, "%H"),
invoice_minute = format(invoice_dttm, "%M"),
invoice_woy = format(invoice_dttm, "%V"),
invoice_ym = format(invoice_dttm, "%Y%m"),
stock_value = price * quantity
) |>
group_by(invoice_ym) |>
mutate(
invoice_monthprop = as.numeric(invoice_dom) / max(as.numeric(invoice_dom))
) |>
ungroup() |>
arrange(invoice_dttm)
data_tbl |> glimpse()
```
# Perform Basic Checks on Data
We now want to look at some very high level checks on the data, and we leverage
some of the functionality provided by `DataExplorer`.
## Create High-Level Visualisations
We first want to look at a visualisation of some high-level summarys of the
meta-data on this dataset. This gives us a quick view of the categorical and
numeric values in the dataset, as well as the proportions of missing values.
```{r plot_dataexp_introduce}
#| echo: true
data_tbl |>
plot_intro(
title = "High Level Table Summary",
ggtheme = theme_cowplot()
)
```
## Check Missing Values
Before we do anything with the data, we first check for missing values
in the dataset. In some cases, missing data is coded by a special
character rather than as a blank, so we first correct for this.
```{r replace_missing_character}
#| echo: true
### _TEMPLATE_
### ADD CODE TO CORRECT FOR DATA ENCODING HERE
```
With missing data properly encoded, we now visualise the missing data in a
number of different ways.
### Univariate Missing Data
```{r plot_univariate_missing_data}
#| echo: true
data_tbl |>
plot_missing(
title = "Summary of Data Missingness",
group = list(Good = 0.05, Acceptable = 0.2, Bad = 0.8, Remove = 1),
ggtheme = theme_cowplot()
)
```
We now want to repeat this plot but only for those columns that have some
missing values.
```{r plot_univariate_missing_only_data}
#| echo: true
data_tbl |>
plot_missing(
title = "Summary of Data Missingness (missing variables only)",
missing_only = TRUE,
group = list(Good = 0.05, Acceptable = 0.2, Bad = 0.8, Remove = 1),
ggtheme = theme_cowplot()
)
```
### Multivariate Missing Data
It is useful to get an idea of what combinations of variables tend to have
variables with missing values simultaneously, so to construct a visualisation
for this we create a count of all the times given combinations of variables
have missing values, producing a heat map for these combination counts.
```{r missing_data_matrix}
#| echo: true
dataexp_missing_group_count <- 20
row_count <- rawdata_tbl |> nrow()
count_nas <- ~ .x |> are_na() |> vec_cast(integer())
missing_vizdata_tbl <- rawdata_tbl |>
mutate(across(everything(), count_nas)) %>% # Need %>% for the '.' functionality
mutate(label = pmap_chr(., str_c)) |>
group_by(label) |>
mutate(
miss_count = n(),
miss_prop = miss_count / row_count
) |>
slice_max(order_by = miss_prop, n = 1, with_ties = FALSE) |>
ungroup() |>
pivot_longer(
!c(label, miss_count, miss_prop),
names_to = "variable_name",
values_to = "presence"
) |>
mutate(
prop_label = sprintf("%6.4f", miss_prop)
)
top10_data_tbl <- missing_vizdata_tbl |>
select(label, miss_prop) |>
distinct() |>
slice_max(order_by = miss_prop, n = dataexp_missing_group_count)
missing_plot_tbl <- missing_vizdata_tbl |>
semi_join(top10_data_tbl, by = "label")
ggplot(missing_plot_tbl) +
geom_tile(aes(x = variable_name, y = prop_label, fill = presence), height = 0.8) +
scale_fill_continuous() +
scale_x_discrete(position = "top", labels = abbreviate) +
xlab("Variable") +
ylab("Proportion of Rows") +
theme(
legend.position = "none",
axis.text.x = element_text(angle = 90, vjust = 0.5)
)
```
This visualisation takes a little explaining.
Each row represents a combination of variables with simultaneous missing
values. For each row in the graphic, the coloured entries show which particular
variables are missing in that combination. The proportion of rows with that
combination is displayed in both the label for the row and the colouring for
the cells in the row.
## Inspect High-level-count Categorical Variables
With the raw data loaded up we now remove obvious unique or near-unique
variables that are not amenable to basic exploration and plotting.
```{r find_highlevelcount_categorical_variables}
#| echo: true
coltype_lst <- create_coltype_list(data_tbl)
count_levels <- ~ .x |> unique() |> length()
catvar_valuecount_tbl <- data_tbl |>
summarise(
.groups = "drop",
across(coltype_lst$split$discrete, count_levels)
) |>
pivot_longer(
cols = everything(),
names_to = "var_name",
values_to = "level_count"
) |>
arrange(desc(level_count))
print(catvar_valuecount_tbl)
row_count <- data_tbl |> nrow()
cat(glue("Dataset has {row_count} rows\n"))
```
Now that we a table of the counts of all the categorical variables we can
automatically exclude unique variables from the exploration, as the level
count will match the row count.
```{r remove_id_variables}
#| echo: true
unique_vars <- catvar_valuecount_tbl |>
filter(level_count == row_count) |>
pull(var_name)
print(unique_vars)
explore_data_tbl <- data_tbl |>
select(-one_of(unique_vars))
```
Having removed the unique identifier variables from the dataset, we
may also wish to exclude categoricals with high level counts also, so
we create a vector of those variable names.
```{r collect_highcount_variables}
#| echo: true
highcount_vars <- catvar_valuecount_tbl |>
filter(level_count >= dataexp_level_exclusion_threshold,
level_count < row_count) |>
pull(var_name)
cat(str_c(highcount_vars, collapse = ", "))
```
We now can continue doing some basic exploration of the data. We may
also choose to remove some extra columns from the dataset.
```{r drop_variables}
#| echo: true
### You may want to comment out these next few lines to customise which
### categoricals are kept in the exploration.
drop_vars <- c(highcount_vars)
if (length(drop_vars) > 0) {
explore_data_tbl <- explore_data_tbl |>
select(-one_of(drop_vars))
cat(str_c(drop_vars, collapse = ", "))
}
```
```{r}
#| echo: FALSE
#knitr::knit_exit()
```
# Univariate Data Exploration
Now that we have loaded the data we can prepare it for some basic data
exploration.
```{r create_log_univariate_data_exploration}
#| echo: true
syslog(
glue("Performing univariate data exploration"),
level = "INFO"
)
```
## Quick Univariate Data Summaries
We use a number of summary visualisations provided by `DataExplorer`: a
facet plot across each variable with categorical variables getting bar plots
and numerical plots getting histograms.
We first look at the barplots of categorical variables.
```{r plot_dataexp_bar}
#| echo: true
#| message: TRUE
plot_bar(
data_tbl,
ncol = 2,
nrow = 2,
title = "Barplots of Data",
ggtheme = theme_cowplot()
)
```
We then have a quick look at histograms of the numeric variables.
```{r plot_dataexp_hist}
#| echo: true
#| message: TRUE
plot_histogram(
data_tbl,
ncol = 2,
nrow = 2,
title = "Histograms of Data",
ggtheme = theme_cowplot()
)
```
Finally, we split the remaining variables into different categories and then
produce a sequence of plots for each variable.
```{r separate_exploration_cols}
#| echo: true
coltype_lst <- create_coltype_list(explore_data_tbl)
print(coltype_lst)
```
## Logical Variables
Logical variables only take two values: TRUE or FALSE. It is useful to see
missing data as well though, so we also plot the count of those.
```{r create_univariate_logical_plots}
#| echo: true
#| warning: FALSE
logical_vars <- coltype_lst$split$logical |> sort()
for (plot_varname in logical_vars) {
cat("--\n")
cat(glue("{plot_varname}\n"))
na_count <- explore_data_tbl |> pull(.data[[plot_varname]]) |> are_na() |> sum()
plot_title <- glue("Barplot of Counts for Variable: {plot_varname} ({na_count} missing values)")
explore_plot <- ggplot(explore_data_tbl) +
geom_bar(aes(x = .data[[plot_varname]])) +
xlab(plot_varname) +
ylab("Count") +
scale_y_continuous(labels = label_comma()) +
ggtitle(plot_title) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
plot(explore_plot)
}
```
## Numeric Variables
Numeric variables are usually continuous in nature, though we also have
integer data.
```{r create_univariate_numeric_plots}
#| echo: true
#| warning: FALSE
numeric_vars <- coltype_lst$split$continuous |> sort()
for (plot_varname in numeric_vars) {
cat("--\n")
cat(glue("{plot_varname}\n"))
plot_var <- explore_data_tbl |> pull(.data[[plot_varname]])
na_count <- plot_var |> are_na() |> sum()
plot_var |> summary() |> print()
plot_title <- glue("Histogram Plot for Variable: {plot_varname} ({na_count} missing values)")
all_plot <- ggplot() +
geom_histogram(aes(x = plot_var), bins = dataexp_hist_bins_count) +
geom_vline(xintercept = mean(plot_var, na.rm = TRUE),
colour = "red", size = 1.5) +
geom_vline(xintercept = median(plot_var, na.rm = TRUE),
colour = "green", size = 1.5) +
xlab(plot_varname) +
ylab("Count") +
scale_x_continuous(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
ggtitle(
plot_title,
subtitle = "(red line is mean, green line is median)"
)
pos_data_tbl <- explore_data_tbl |>
filter(.data[[plot_varname]] >= 0) |>
mutate(var_val = abs(.data[[plot_varname]]))
pos_log_plot <- ggplot(pos_data_tbl) +
geom_histogram(aes(x = var_val), bins = dataexp_hist_bins_count) +
xlab(plot_varname) +
ylab("Count") +
scale_x_log10(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
ggtitle("Positive Values")
neg_data_tbl <- explore_data_tbl |>
filter(.data[[plot_varname]] < 0) |>
mutate(var_val = abs(.data[[plot_varname]]))
neg_log_plot <- ggplot(neg_data_tbl) +
geom_histogram(aes(x = var_val), bins = dataexp_hist_bins_count) +
xlab(plot_varname) +
ylab("Count") +
scale_x_log10(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
ggtitle("Negative Values")
plot_grid(
all_plot,
NULL,
pos_log_plot,
neg_log_plot,
nrow = 2
) |>
print()
}
```
## Categorical Variables
Categorical variables only have values from a limited, and usually fixed,
number of possible values
```{r create_univariate_categorical_plots}
#| echo: true
#| warning: FALSE
categorical_vars <- coltype_lst$split$discrete |> sort()
for (plot_varname in categorical_vars) {
cat("--\n")
cat(glue("{plot_varname}\n"))
na_count <- explore_data_tbl |> pull(.data[[plot_varname]]) |> are_na() |> sum()
plot_title <- glue("Barplot of Counts for Variable: {plot_varname} ({na_count} missing values)")
standard_plot_tbl <- explore_data_tbl |>
count(.data[[plot_varname]])
standard_plot <- ggplot(standard_plot_tbl) +
geom_bar(aes(x = .data[[plot_varname]], weight = n)) +
xlab(plot_varname) +
ylab("Count") +
scale_x_discrete(labels = ~ abbreviate(.x, minlength = 10)) +
scale_y_continuous(labels = label_comma()) +
ggtitle(plot_title) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
standard_plot |> print()
desc_plot_tbl <- explore_data_tbl |>
pull(.data[[plot_varname]]) |>
fct_lump(n = dataexp_cat_level_count) |>
fct_count() |>
mutate(f = fct_relabel(f, str_trunc, width = 15))
desc_plot <- ggplot(desc_plot_tbl) +
geom_bar(aes(x = fct_reorder(f, -n), weight = n)) +
xlab(plot_varname) +
ylab("Count") +
scale_x_discrete(labels = abbreviate) +
scale_y_continuous(labels = label_comma()) +
ggtitle(plot_title) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
desc_plot |> print()
}
```
## Date/Time Variables
Date/Time variables represent calendar or time-based data should as time of the
day, a date, or a timestamp.
```{r create_univariate_datetime_plots}
#| echo: true
#| warning: FALSE
datetime_vars <- coltype_lst$split$datetime |> sort()
for (plot_varname in datetime_vars) {
cat("--\n")
cat(glue("{plot_varname}\n"))
plot_var <- explore_data_tbl |> pull(.data[[plot_varname]])
na_count <- plot_var |> are_na() |> sum()
plot_var |> summary() |> print()
plot_title <- glue("Barplot of Dates/Times in Variable: {plot_varname} ({na_count} missing values)")
explore_plot <- ggplot(explore_data_tbl) +
geom_histogram(aes(x = .data[[plot_varname]]), bins = dataexp_hist_bins_count) +
xlab(plot_varname) +
ylab("Count") +
scale_y_continuous(labels = label_comma()) +
ggtitle(plot_title)
plot(explore_plot)
}
```
```{r, echo=FALSE}
#| echo: FALSE
#knitr::knit_exit()
```
# Bivariate Facet Plots
We now move on to looking at bivariate plots of the data set.
```{r create_log_bivariate_facet_plots}
#| echo: true
syslog(
glue("Performing bivariate facet plots"),
level = "INFO"
)
```
A natural way to explore relationships in data is to create univariate
visualisations facetted by a categorical value.
```{r bivariate_facet_data}
#| echo: true
facet_varname <- "invoice_month"
dataexp_facet_count_max <- 3
```
## Logical Variables
For logical variables we facet on barplots of the levels, comparing TRUE,
FALSE and missing data.
```{r create_bivariate_logical_plots}
#| echo: true
logical_vars <- logical_vars[!logical_vars %in% facet_varname] |> sort()
for (plot_varname in logical_vars) {
cat("--\n")
cat(plot_varname)
plot_tbl <- data_tbl |> filter(!are_na(.data[[plot_varname]]))
explore_plot <- ggplot(plot_tbl) +
geom_bar(aes(x = .data[[plot_varname]])) +
facet_wrap(facet_varname, scales = "free") +
xlab(plot_varname) +
ylab("Count") +
scale_y_continuous(labels = label_comma()) +
ggtitle(glue("{facet_varname}-Faceted Histogram for Variable: {plot_varname}")) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
plot(explore_plot)
}
```
## Numeric Variables
For numeric variables, we facet on histograms of the data.
```{r create_bivariate_numeric_plots}
#| echo: true
for (plot_varname in numeric_vars) {
cat("--\n")
cat(plot_varname)
plot_tbl <- data_tbl |> filter(!are_na(.data[[plot_varname]]))
explore_plot <- ggplot(plot_tbl) +
geom_histogram(aes(x = .data[[plot_varname]]), bins = dataexp_hist_bins_count) +
facet_wrap(facet_varname, scales = "free") +
xlab(plot_varname) +
ylab("Count") +
scale_x_continuous(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
ggtitle(glue("{facet_varname}-Faceted Histogram for Variable: {plot_varname}")) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
print(explore_plot)
}
```
## Categorical Variables
We treat categorical variables like logical variables, faceting the barplots
of the different levels of the data.
```{r create_bivariate_categorical_plots}
#| echo: true
categorical_vars <- categorical_vars[!categorical_vars %in% facet_varname] |> sort()
for (plot_varname in categorical_vars) {
cat("--\n")
cat(plot_varname)
plot_tbl <- data_tbl |>
filter(!are_na(.data[[plot_varname]])) |>
mutate(
varname_trunc = fct_relabel(.data[[plot_varname]], str_trunc, width = 10)
)
explore_plot <- ggplot(plot_tbl) +
geom_bar(aes(x = varname_trunc)) +
facet_wrap(facet_varname, scales = "free") +
xlab(plot_varname) +
ylab("Count") +
scale_x_discrete(labels = abbreviate) +
scale_y_continuous(labels = label_comma()) +
ggtitle(glue("{facet_varname}-Faceted Histogram for Variable: {plot_varname}")) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
plot(explore_plot)
}
```
## Date/Time Variables
Like the univariate plots, we facet on histograms of the years in the dates.
```{r create_bivariate_datetime_plots}
#| echo: true
for (plot_varname in datetime_vars) {
cat("--\n")
cat(plot_varname)
plot_tbl <- data_tbl |> filter(!are_na(.data[[plot_varname]]))
explore_plot <- ggplot(plot_tbl) +
geom_histogram(aes(x = .data[[plot_varname]]), bins = dataexp_hist_bins_count) +
facet_wrap(facet_varname, scales = "free") +
xlab(plot_varname) +
ylab("Count") +
scale_y_continuous(labels = label_comma()) +
ggtitle(glue("{facet_varname}-Faceted Histogram for Variable: {plot_varname}")) +
theme(axis.text.x = element_text(angle = 30, vjust = 0.5))
plot(explore_plot)
}
```
```{r free_memory_facetplot}
#| echo: FALSE
rm(plot_var, plot_tbl)
```
```{r}
#| echo: true
#knitr::knit_exit()
```
# Custom Explorations
In this section we perform various data explorations.
```{r create_log_custom_explorations}
#| echo: true
syslog(
glue("Performing custom data exploration"),
level = "INFO"
)
```
## Custom Checks for Data Integrity
We want to check the transaction data for consistency, so we create a table
of all distinct
```{r check_stock_codes}
#| echo: true
stock_codes_lookup_tbl <- data_tbl |>
select(stock_code_upr, description) |>
distinct() |>
arrange(stock_code_upr, description) |>
drop_na(description)
stock_codes_lookup_tbl |> glimpse()
```
We now take a look at the first 50 rows of this table to get a sense of any
possible duplication of `stock_code`.
```{r plot_stock_codes_distinct_50}
#| echo: true
stock_codes_lookup_tbl |> datatable()
```
### Items per Transactions
As another check on the data, we want to look at how many different objects
are included in
```{r plot_histogram_distinct_items}
#| echo: true
plot_tbl <- data_tbl |>
filter(quantity > 0) |>
count(invoice_id, name = "n_items")
ggplot(plot_tbl) +
geom_histogram(aes(x = n_items), bins = 40) +
scale_x_log10(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
xlab("Number of Items") +
ylab("Transaction Count") +
ggtitle("Histogram of Item Counts per Transactions")
```
## Explore Aggregate Amounts
We now turn our focus to aggregating the data set in various ways and inspect
how these aggregate totals are distributed.
### Invoice-Level Amounts
We first aggregate the data at the invoice level, and inspect how those amounts
are distributed.
```{r explore_invoice_amounts}
#| echo: true
invoice_data_tbl <- data_tbl |>
group_by(invoice_id) |>
summarise(
.groups = "drop",
invoice_amount = sum(price * quantity) |> round(2)
)
invoice_mean <- invoice_data_tbl |> pull(invoice_amount) |> mean() |> round(2)
invoice_median <- invoice_data_tbl |> pull(invoice_amount) |> median() |> round(2)
ggplot(invoice_data_tbl) +
geom_histogram(aes(x = invoice_amount), bins = 50) +
geom_vline(aes(xintercept = invoice_mean), colour = "black") +
geom_vline(aes(xintercept = invoice_median), colour = "red") +
xlab("Invoice Amount") +
ylab("Count") +
scale_x_log10(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
ggtitle(
label = "Histogram Plot for Invoice Amount",
subtitle = glue("Mean is {invoice_mean}, Median is {invoice_median}")
)
```
We see there is a broad range of different invoice totals, with mean and
median being a few hundred pounds.
### Customer-Level Amounts
```{r explore_customer_amounts}
#| echo: true
customer_data_tbl <- data_tbl |>
group_by(customer_id) |>
summarise(
.groups = "drop",
customer_spend = sum(price * quantity) |> round(2)
)
ggplot(customer_data_tbl) +
geom_histogram(aes(x = customer_spend), bins = 50) +
xlab("Customer Spend") +
ylab("Count") +
scale_x_log10(labels = label_comma()) +
scale_y_continuous(labels = label_comma()) +
ggtitle("Histogram Plot for Customer Spend")
```
```{r customer_spend_hill_plot}