-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_summaries_r.qmd
More file actions
2150 lines (1546 loc) · 87.1 KB
/
data_summaries_r.qmd
File metadata and controls
2150 lines (1546 loc) · 87.1 KB
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: "Data Summaries in R"
author: "Wade K. Copeland"
date: last-modified
date-format: "MMMM DD, YYYY"
output-file: index.html
bibliography: references.bib
format:
html:
embed-resources: true
code-overflow: wrap
page-layout: full
code-fold: false
toc: true
toc-location: left
toc-depth: 2
toc-expand: 2
html-math-method: katex
code-tools:
source: true
toggle: true
caption: "Source Code"
number-sections: false
appendix-style: plain
engine: jupyter
knitr:
opts_knit:
root.dir: "./"
---
<!-- To Do -->
<!-- What if no label? -->
<!-- Objects of class POSIXct and POSIXt -->
<!-- Error on not having difftime units defined for date objects -->
<!-- Don't know how to automatically pick scale for object of type labelled/integer. Defaulting to continuous. -->
# Introduction
An essential part of any data analysis project is to understand the data at hand. For this task, we will create a function that takes as input a variable from the data, a categorical variable to describe by, and returns summary tables and plots.
This tutorial uses the R programming language [@Rlang2019]. All of the files needed to reproduce these results can be downloaded from the Git repository <a href="https://github.com/wkingc/data-summaries-r/" target="_blank">https://github.com/wkingc/data-summaries-r</a>.
# Required Libraries
The libraries <i>knitr</i>, <i>bookdown</i>, and <i>kableExtra</i> are used to generate the HTML output [@knitr; @bookdown; @kableExtra]. The <i>ggplot2</i> library is loaded for the example data set that is used in this tutorial [@ggplot2]. The <i>Hmisc</i> library provides functionality needed to create variable labels [@Hmisc]. The libraries <i>reshape2</i> and <i>dplyr</i> are loaded for their data manipulation funtions [@dplyr; @reshape2].
```{r libraries, eval = TRUE, echo = TRUE, results = FALSE, warning = FALSE, message = FALSE}
library("knitr")
library("bookdown")
library("kableExtra")
library("ggplot2")
library("Hmisc")
library("reshape2")
library("dplyr")
```
# Example Data Setup
The data set used in this tutorial is <b>mpg</b> from the <i>ggplot2</i> package. From the description in the manual:
> This dataset contains a subset of the fuel economy data that the EPA makes available <a href="http://fueleconomy.gov" target="_blank">here</a>. It contains only models which had a new release every year between 1999 and 2008 - this was used as a proxy for the popularity of the car.
```{r ExampleDataSetup, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
set.seed(123)
data(mpg)
mpg <- data.frame(mpg)
colnames(mpg)[which(colnames(mpg) == "manufacturer")] <- "manu"
mpg$manu <- factor(mpg$manu)
mpg$model <- factor(mpg$model)
mpg$displ <- as.numeric(mpg$displ)
mpg$year <- factor(mpg$year, levels = c("1999", "2008"), ordered = TRUE)
mpg$dp <- as.Date(NA, origin = "1970-01-01")
mpg$dp[which(mpg$year == "1999")] <- sample(seq(as.Date('1999-01-01', format = "%Y-%m-%d", origin = "1970-01-01"), as.Date('1999-12-25', format = "%Y-%m-%d", origin = "1970-01-01"), by="day"), dim(mpg)[1]/2)
mpg$dp[which(mpg$year == "2008")] <- sample(seq(as.Date('2008-01-01', format = "%Y-%m-%d", origin = "1970-01-01"), as.Date('2008-12-25', format = "%Y-%m-%d", origin = "1970-01-01"), by="day"), dim(mpg)[1]/2)
mpg$dp[sample(1:length(mpg$dp), size = 20)] <- NA
mpg$dp[10] <- as.Date('1000-05-02', format = "%Y-%m-%d", origin = "1970-01-01")
mpg$dplt <- as.POSIXlt(NA, origin = "1970-01-01 0:0:0")
mpg$dplt[which(mpg$year == "1999")] <- sample(seq(as.POSIXlt('1999-01-01 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), as.POSIXlt('1999-12-25 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), by="min"), dim(mpg)[1]/2)
mpg$dplt[which(mpg$year == "2008")] <- sample(seq(as.POSIXlt('2008-01-01 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), as.POSIXlt('2008-12-25 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), by="sec"), dim(mpg)[1]/2)
mpg$dplt[sample(1:length(mpg$dplt), size = 20)] <- NA
mpg$dpct <- as.POSIXct(NA, origin = "1970-01-01 0:0:0")
mpg$dpct[which(mpg$year == "1999")] <- sample(seq(as.POSIXct('1999-01-01 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), as.POSIXct('1999-12-25 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), by="min"), dim(mpg)[1]/2)
mpg$dpct[which(mpg$year == "2008")] <- sample(seq(as.POSIXct('2008-01-01 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), as.POSIXct('2008-12-25 0:0:0', format = "%Y-%m-%d %H:%M:%S", origin = "1970-01-01 0:0:0"), by="sec"), dim(mpg)[1]/2)
mpg$dpct[sample(1:length(mpg$dpct), size = 20)] <- NA
mpg$cyl <- factor(mpg$cyl, levels = c(4, 5, 6, 8), ordered = TRUE)
mpg$trans <- factor(mpg$trans)
mpg$drv <- factor(mpg$drv, levels = c("f", "r", "4"), labels = c("front-wheel drive", "rear wheel drive", "4wd"))
mpg$fl <- factor(mpg$fl)
mpg$class <- factor(mpg$class)
mpg$rn <- rnorm(dim(mpg)[1], mean = 10, sd = 5)
mpg$rn[sample(1:length(mpg$rn), size = 50)] <- NA
mpg$rdifftime <- rnorm(dim(mpg)[1], mean = 10, sd = 5)
mpg$rdifftime[sample(1:length(mpg$rdifftime), size = 50)] <- NA
mpg$rdifftime <- as.difftime(mpg$rdifftime, units = "weeks")
mpg$rdifftime[which(mpg$rdifftime < 0)] <- 0
mpg$logical <- mpg$rdifftime >= 10
mpg$party <- factor(sample(c("republican", "democrat", "independent", NA), dim(mpg)[1], replace = TRUE), levels = c("republican", "democrat", "independent"))
mpg$comments <- sample(c("I like this car!", "Meh.", "This is the worst car ever!", "Does it come in green?", "want cheese flavoured cars.", "Does it also fly?", "Blah, Blah, Blah, Blah, Blah, Blah, Blah, Blah", "Missing", ".", NA), dim(mpg)[1], replace = TRUE)
mpg$miss <- NA
label(mpg$manu) <- "manufacturer"
label(mpg$model) <- "model name"
label(mpg$displ) <- "engine displacement, in litres"
label(mpg$year) <- "year of manufacture"
label(mpg$dp) <- "date of purchase (Date class)"
label(mpg$dplt) <- "date of purchase (POSIXlt class)"
label(mpg$dpct) <- "date of purchase (POSIXct class)"
label(mpg$cyl) <- "number of cylinders"
label(mpg$trans) <- "type of transmission"
label(mpg$drv) <- "drive type"
label(mpg$cty) <- "city miles per gallon"
label(mpg$hwy) <- "highway miles per gallon"
label(mpg$fl) <- "fuel type"
label(mpg$class) <- "type of car"
label(mpg$rn) <- "some random numbers that are generated from a normal distrubtion with mean = 10 and sd = 5"
label(mpg$rdifftime) <- "some random numbers that are generated from a normal distrubtion with mean = 10 and sd = 5, and then converted to weeks"
label(mpg$logical) <- "some random numbers that are generated from a normal distrubtion with mean = 10 and sd = 5, and then converted to weeks, and then set to TRUE if the difference is greater than 10"
label(mpg$party) <- "some random political parties"
label(mpg$comments) <- "some random comments"
label(mpg$miss) <- "an all missing variable"
kable(head(mpg), caption = "Header of <b>mpg</b>.", booktabs = TRUE, escape = FALSE) %>% kable_styling(bootstrap_options = c("striped", "hover", "condensed", "responsive"))
```
# Data Summary Function
Below are a set of functions I wrote to using S4 (see <a href="https://www.cyclismo.org/tutorial/R/s4Classes.html" target="_blank">https://www.cyclismo.org/tutorial/R/s4Classes.html</a> for a gentle introduction to object oriented programming in R), culminating into a single function called <b>data_summary</b>. The basic structure uses an object of class <i>dataSummaries</i> and then, based on the class of <b>x</b>, the <i>dataSummariesSetup</i> method applied to the <i>dataSummaries</i> class, returns an object of class <i>dataSummariesCharacter</i>, <i>dataSummariesNumeric</i>, <i>dataSummariesDate</i>, or <i>dataSummariesDifftime</i>. Each of these four output classes inherits from the <i>dataSummaries</i> class; thus any method written for <i>dataSummaries</i> also applies to the four classes that inherit from it.
As input the <b>data_summary</b> function takes a variable to summarize (<b>x</b>), an optional variable or variables (as a character string) to summarize by (<b>by</b>), the data (<b>data</b>), and the units to use for <i>difftime</i> if <b>x</b> refers to a <i>Date</i>, <i>POSIXlt</i>, <i>POSIXct</i>, or <i>difftime</i> object in the <b>data</b>.
As output, the function returns an object of class <i>dataSummaries</i>. The function has a <i>show</i> method and a method called <i>make_output</i> that generates <i>knitr</i> friendly output. The summary table and plot can also be accessed individually through their accessor functions, <i>data_summary_table</i>, and <i>data_summary_plot</i>, respectively.
```{r dataSummaryFun, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
setOldClass(c("ggplot", "gg"))
dataSummaries <- setClass(
"dataSummaries",
slots = c(
x = "character",
by = "character",
data = "data.frame",
difftime_units = "character",
xLab = "character",
byLab = "character",
table = "data.frame",
plot = "ANY"
),
prototype = list(
x = character(0),
by = character(0),
data = data.frame(),
difftime_units = character(0),
xLab = character(0),
byLab = character(0),
table = data.frame(),
plot = NULL
),
)
invisible(setValidity("dataSummaries", function(object) {
if (!is.null(object@plot) && !inherits(object@plot, "ggplot")) {
return("The 'plot' slot must be a ggplot object or NULL.")
}
TRUE
}))
dataSummariesCharacter <- setClass(
"dataSummariesCharacter",
slots = c(
type = "character"
),
prototype = list(
type = character(0)
),
contains = "dataSummaries"
)
dataSummariesNumeric <- setClass(
"dataSummariesNumeric",
slots = c(
type = "character"
),
prototype = list(
type = character(0)
),
contains = "dataSummaries"
)
dataSummariesDate <- setClass(
"dataSummariesDate",
slots = c(
type = "character"
),
prototype = list(
type = character(0)
),
contains = "dataSummaries"
)
dataSummariesDifftime <- setClass(
"dataSummariesDifftime",
slots = c(
type = "character"
),
prototype = list(
type = character(0)
),
contains = "dataSummaries"
)
invisible(setGeneric(name = "dataSummariesSetup", def = function(object) standardGeneric("dataSummariesSetup")))
setMethod(
f = "dataSummariesSetup",
signature = "dataSummaries",
definition = function(object)
{
x = object@x
by = object@by
data = object@data
xLab <- label(data[, x])
colnames(data)[which(colnames(data) == x)] <- "var"
if (length(by) == 0) {
data$by <- factor(data$by <- "")
label(data$by) <- ""
byLab <- label(data$by)
} else {
data$by <- interaction(data[, by], sep = ", ")
byLab <- paste(label(data[, by]), collapse = " by ")
overall <- data
overall$by <- "Overall"
data <- rbind(data, overall)
}
data <- data[, c("var", "by")]
if ("labelled" %in% class(data$var)) {
class(data$var) <- class(data$var)[(-1)*which(class(data$var) == "labelled")]
}
object@xLab <- xLab
object@byLab <- byLab
object@data <- data
if (any(c("character", "factor", "logical") %in% class(data$var))) {
return(dataSummariesCharacter(object, type = class(data$var)))
} else if (any(c("numeric", "integer") %in% class(data$var))) {
return(dataSummariesNumeric(object, type = class(data$var)))
} else if (any(c("Date", "POSIXlt", "POSIXct", "POSIXt") %in% class(data$var))) {
if (length(object@difftime_units) == 0) stop("You need to specify the units for the difference in time. See help(difftime) for additional information.")
return(dataSummariesDate(object, type = class(data$var)))
} else if ("difftime" %in% class(data$var)) {
if (length(object@difftime_units) == 0) stop("You need to specify the units for the difference in time. See help(difftime) for additional information.")
return(dataSummariesDifftime(object, type = class(data$var)))
} else {
stop("x is an unsupported class")
}
}
)
invisible(setGeneric(name = "data_summary_switch", def = function(object) standardGeneric("data_summary_switch")))
setMethod(
f = "data_summary_switch",
signature = "dataSummariesCharacter",
definition = function(object)
{
xLab <- object@xLab
byLab <- object@byLab
data <- object@data
freqs <- table(data$var, data$by, useNA = "ifany", dnn = c(xLab, byLab))
rownames(freqs)[which(is.na(rownames(freqs)))] <- "R NA Value"
colnames(freqs)[which(is.na(colnames(freqs)))] <- "R NA Value"
props <- round(100*prop.table(freqs, 2), 2)
res <- freqs
for (i in 1:dim(freqs)[2]) {
res[, i] <- paste(freqs[, i], " (", props[, i], "%)", sep = "")
}
res <- as.data.frame(res)
colnames(res) <- c("var", "by", "freq")
res <- dcast(res, var ~ by, value.var = "freq")
colnames(res)[1] <- xLab
if (byLab == "") colnames(res)[2] <- "n (%)"
pData <- as.data.frame(props)
colnames(pData) <- c("var", "by", "freq")
levs <- as.character(pData$var)
tmp <- nchar(levs)
strCombRes <- list()
for (k in 1:length(levs)) {
strRes <- list()
j = 0
for (i in 1:ceiling(max(tmp)/30)) {
strRes[[i]] <- substr(levs[k], j, 30*i)
j = 30*i + 1
}
strCombRes[[k]] <- unlist(strRes)
}
foo <- function(x) {
if (!(length(which(x == "")) == 0)) x <- x[-1*which(x == "")]
x <- paste(x, collapse = "\n")
return(x)
}
levs <- unlist(lapply(strCombRes, foo))
pData$names <- factor(rownames(pData), levels = rownames(pData), labels = levs)
pData <- pData[, -1]
colfunc <- colorRampPalette(c("#e41a1c","#377eb8","#4daf4a","#984ea3","#ff7f00"))
colors <- colfunc(length(levels(pData$names)))
p = ggplot(data = pData, aes(x = by, y = freq, fill = names)) +
scale_fill_manual(values = colors) +
geom_bar(stat = "identity") +
xlab(paste(strwrap(xLab, width = 60), collapse = "\n")) +
ylab("Percent") +
theme(
axis.line = element_line(colour = "black"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
axis.text = element_text(size = 12),
axis.text.x = element_text(angle = 50, hjust = 1),
axis.title = element_text(size = 12),
legend.title = element_blank(),
legend.position = "right",
panel.grid = element_line(color = "lightgray"),
panel.background = element_rect(fill = "white", colour = "white"))
object@table <- res
object@plot <- p
return(object)
}
)
setMethod(
f = "data_summary_switch",
signature = "dataSummariesNumeric",
definition = function(object)
{
xLab <- object@xLab
byLab <- object@byLab
data <- object@data
if (any(is.na(data$by))) {
byLevs <- levels(data$by)
data$by <- as.character(data$by)
data$by[which(is.na(as.character(data$by)))] <- "R NA Value"
data$by <- factor(data$by, levels = c(byLevs, "R NA Value"))
}
percMiss <- function(x) res <- round((length(which(is.na(x)))/length(x))*100, 2)
res <- data %>%
group_by(by) %>%
summarize(
label = xLab,
n = length(na.omit(var)),
miss = percMiss(var),
mean = round(mean(var, na.rm = TRUE), 2),
sd = round(sd(var, na.rm = TRUE), 2),
median = round(median(var, na.rm = TRUE), 2),
mad = round(mad(var, na.rm = TRUE), 2),
q25 = round(quantile(var, probs = 0.25, na.rm = TRUE, type = 1), 2),
q75 = round(quantile(var, probs = 0.75, na.rm = TRUE, type = 1), 2),
IQR = round(IQR(var, na.rm = TRUE), 2),
min = round(min(var, na.rm = TRUE), 2),
max = round(max(var, na.rm = TRUE), 2)
)
res <- data.frame(res)
colnames(res) <- c(byLab, "Label", "N", "P NA", "Mean", "S Dev", "Med", "MAD", "25th P", "75th P", "IQR", "Min", "Max")
pData <- na.omit(data.frame(data[, c("var", "by")]))
p = ggplot(data = pData, aes(x = by, y = var)) +
geom_boxplot(position = position_dodge(1), fill = "#2c7bb6") +
xlab(byLab) +
ylab(paste(strwrap(xLab, width = 40), collapse = "\n")) +
theme(
axis.line = element_line(colour = "black"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
legend.position = "none",
axis.text = element_text(size = 12),
axis.text.x = element_text(angle = 50, hjust = 1),
axis.title = element_text(size = 12),
panel.grid = element_line(color = "lightgray"),
panel.background = element_rect(fill = "white", colour = "white"))
object@table <- res
object@plot <- p
return(object)
}
)
setMethod(
f = "data_summary_switch",
signature = "dataSummariesDate",
definition = function(object)
{
xLab <- object@xLab
byLab <- object@byLab
data <- object@data
difftime_units <- object@difftime_units
if (any(is.na(data$by))) {
byLevs <- levels(data$by)
data$by <- as.character(data$by)
data$by[which(is.na(as.character(data$by)))] <- "R NA Value"
data$by <- factor(data$by, levels = c(byLevs, "R NA Value"))
}
percMiss <- function(x) round((length(which(is.na(x)))/length(x))*100, 2)
sdDate <- function(x) {
res <- difftime(x, mean(x, na.rm = TRUE), units = "secs")
res <- as.numeric(as.character(res))
res <- sd(res, na.rm = TRUE)
res <- as.difftime(res, units = "secs")
units(res) <- difftime_units
return(res)
}
sdDate(data$var)
madDate <- function(x) {
res <- difftime(x, mean(x, na.rm = TRUE), units = "secs")
res <- as.numeric(as.character(res))
res <- mad(res, na.rm = TRUE)
res <- as.difftime(res, units = "secs")
units(res) <- difftime_units
return(res)
}
dquantile <- function(x, probs){
sx <- sort(x)
pos <- round(probs*length(x))
return(sx[pos])
}
q25Date <- function(x) dquantile(x, probs = 0.25)
q75Date <- function(x) dquantile(x, probs = 0.75)
IQRdate <- function(x) {
res <- difftime(dquantile(x, probs = 0.75), dquantile(x, probs = 0.25), units = "secs")
units(res) <- difftime_units
return(res)
}
res <- data %>%
group_by(by) %>%
summarize(
label = xLab,
n = length(na.omit(var)),
miss = percMiss(var),
mean = mean(var, na.rm = TRUE),
sd = round(sdDate(var), 2),
median = median(var, na.rm = TRUE),
mad = round(madDate(var), 2),
q25 = q25Date(var),
q75 = q75Date(var),
IQR = IQRdate(var),
min = min(var, na.rm = TRUE),
max = max(var, na.rm = TRUE)
)
res <- data.frame(res)
colnames(res) <- c(byLab, "Label", "N", "P NA", "Mean", "S Dev", "Med", "MAD", "25th P", "75th P", "IQR", "Min", "Max")
pData <- na.omit(data.frame(data[, c("var", "by")]))
if ("POSIXlt" %in% class(pData$var)) pData$var <- as.POSIXct(pData$var)
p = ggplot(data = pData, aes(x = by, y = var)) +
geom_boxplot(position = position_dodge(1), fill = "#2c7bb6") +
xlab(byLab) +
ylab(paste(strwrap(xLab, width = 40), collapse = "\n")) +
theme(
axis.line = element_line(colour = "black"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
legend.position = "none",
axis.text = element_text(size = 12),
axis.text.x = element_text(angle = 50, hjust = 1),
axis.title = element_text(size = 12),
panel.grid = element_line(color = "lightgray"),
panel.background = element_rect(fill = "white", colour = "white"))
object@table <- res
object@plot <- p
return(object)
}
)
setMethod(
f = "data_summary_switch",
signature = "dataSummariesDifftime",
definition = function(object)
{
xLab <- object@xLab
byLab <- object@byLab
data <- object@data
difftime_units <- object@difftime_units
if (any(is.na(data$by))) {
byLevs <- levels(data$by)
data$by <- as.character(data$by)
data$by[which(is.na(as.character(data$by)))] <- "R NA Value"
data$by <- factor(data$by, levels = c(byLevs, "R NA Value"))
}
percMiss <- function(x) res <- round((length(which(is.na(x)))/length(x))*100, 2)
units(data$var) <- "days"
meanDate <- function(x) {
res <- mean(x, na.rm = TRUE)
units(res) <- difftime_units
return(res)
}
medianDate <- function(x) {
res <- median(x, na.rm = TRUE)
units(res) <- difftime_units
return(res)
}
sdDate <- function(x) {
res <- as.difftime(sd(as.numeric(x), na.rm = TRUE), format = "%X", units = "days")
units(res) <- difftime_units
return(res)
}
madDate <- function(x) {
res <- as.difftime(mad(as.numeric(x), na.rm = TRUE), format = "%X", units = "days")
units(res) <- difftime_units
return(res)
}
q25Date <- function(x) {
res <- as.difftime(quantile(as.numeric(x), probs = 0.25, na.rm = TRUE, type = 1), units = "days")
units(res) <- difftime_units
return(res)
}
q75Date <- function(x) {
res <- as.difftime(quantile(as.numeric(x), probs = 0.75, na.rm = TRUE, type = 1), units = "days")
units(res) <- difftime_units
return(res)
}
IQRdate <- function(x) {
res <- as.difftime(IQR(as.numeric(x), na.rm = TRUE), format = "%X", units = "days")
units(res) <- difftime_units
return(res)
}
minDate <- function(x) {
res <- as.difftime(min(as.numeric(x), na.rm = TRUE), format = "%X", units = "days")
units(res) <- difftime_units
return(res)
}
maxDate <- function(x) {
res <- as.difftime(max(as.numeric(x), na.rm = TRUE), format = "%X", units = "days")
units(res) <- difftime_units
return(res)
}
res <- data %>%
group_by(by) %>%
summarize(
label = xLab,
n = length(na.omit(var)),
miss = percMiss(var),
mean = round(meanDate(var), 2),
sd = round(sdDate(var), 2),
median = round(medianDate(var), 2),
mad = round(madDate(var), 2),
q25 = round(q25Date(var), 2),
q75 = round(q75Date(var), 2),
IQR = round(IQRdate(var), 2),
min = round(minDate(var), 2),
max = round(maxDate(var), 2)
)
res <- data.frame(res)
colnames(res) <- c(byLab, "Label", "N", "P NA", "Mean", "S Dev", "Med", "MAD", "25th P", "75th P", "IQR", "Min", "Max")
pData <- na.omit(data.frame(data[, c("var", "by")]))
units(pData$var) <- difftime_units
p = ggplot(data = pData, aes(x = by, y = var)) +
geom_boxplot(position = position_dodge(1), fill = "#2c7bb6") +
xlab(byLab) +
ylab(paste(strwrap(xLab, width = 40), collapse = "\n")) +
theme(
axis.line = element_line(colour = "black"),
panel.border = element_rect(colour = "black", fill = NA, size = 1),
legend.position = "none",
axis.text = element_text(size = 12),
axis.text.x = element_text(angle = 50, hjust = 1),
axis.title = element_text(size = 12),
panel.grid = element_line(color = "lightgray"),
panel.background = element_rect(fill = "white", colour = "white"))
object@table <- res
object@plot <- p
return(object)
}
)
setMethod(
f = "show",
signature = "dataSummaries",
definition = function(object)
{
print(object@table)
print(object@plot)
}
)
invisible(setGeneric(name = "make_kable_output", def = function(object) standardGeneric("make_kable_output")))
setMethod(
f = "make_kable_output",
signature = "dataSummaries",
definition = function(object)
{
if (object@byLab == "") {
print(
kable(
object@table, caption = paste("Summary statistics of ", object@xLab, ".", sep = ""), booktabs = TRUE, table.attr = "data-quarto-disable-processing=true") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = TRUE, font_size = 14))
} else {
print(
kable(
object@table, caption = paste("Summary statistics of ", object@xLab, " by ", object@byLab, ".", sep = ""), booktabs = TRUE, table.attr = "data-quarto-disable-processing=true") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = TRUE, font_size = 14))
}
}
)
invisible(setGeneric(name = "make_complete_output", def = function(object) standardGeneric("make_complete_output")))
setMethod(
f = "make_complete_output",
signature = "dataSummaries",
definition = function(object)
{
if (object@byLab == "") {
print(
kable(
object@table, caption = paste("Summary statistics of ", object@xLab, ".", sep = ""), booktabs = TRUE, table.attr = "data-quarto-disable-processing=true") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = TRUE, font_size = 14))
} else {
print(
kable(
object@table, caption = paste("Summary statistics of ", object@xLab, " by ", object@byLab, ".", sep = ""), booktabs = TRUE, table.attr = "data-quarto-disable-processing=true") %>%
kable_styling(bootstrap_options = c("striped", "hover"), full_width = TRUE, font_size = 14))
}
print(object@plot)
}
)
invisible(setGeneric(name = "data_summary_table", def = function(object) standardGeneric("data_summary_table")))
setMethod(
f = "data_summary_table",
signature = "dataSummaries",
definition = function(object)
{
object@table
}
)
invisible(setGeneric(name = "data_summary_plot", def = function(object) standardGeneric("data_summary_plot")))
setMethod(
f = "data_summary_plot",
signature = "dataSummaries",
definition = function(object)
{
object@plot
}
)
data_summary <- function(x, by = character(0), data, difftime_units = character(0)) {
object = dataSummaries(x = x, data = data, by = by, difftime_units = difftime_units)
object = dataSummariesSetup(object)
object = data_summary_switch(object)
}
```
# Examples
::: {.panel-tabset .tabset-fade .tabset-pills}
## Categorical
::: {.panel-tabset .tabset-fade .tabset-pills}
For a categorical variable <b>x</b>, we only need to specify <b>x</b> and the <b>data</b>.
```{r cylSummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
cylSummaryExample <- data_summary(x = "cyl", data = mpg)
```
### Show method to output table and plot
```{r cylSummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
show(cylSummaryExample)
```
### Output the summary table
```{r cylSummaryExampleTable, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
data_summary_table(cylSummaryExample)
```
### Output the plot
```{r cylSummaryExamplePlot, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
data_summary_plot(cylSummaryExample)
```
### Generate knitr friendly summary table
```{r cylSummaryExampleKnitrTable, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
make_kable_output(cylSummaryExample)
```
### Generate knitr friendly output
```{r cylSummaryExampleComplete, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7, fig.align = 'center', fig.cap = paste("Stacked barplot of ", label(mpg$cyl), ".", sep = "")}
make_complete_output(cylSummaryExample)
```
:::
## Categorical By
::: {.panel-tabset .tabset-fade .tabset-pills}
For a categorical variable with by, we need to specify <b>x</b>, a <b>by</b> variable, and the <b>data</b>.
```{r cylByYearSummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
cylByYearSummaryExample <- data_summary(x = "cyl", by = "year", data = mpg)
```
### Show method to output table and plot
```{r cylByYearSummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
show(cylByYearSummaryExample)
```
### Output the summary table
```{r cylByYearSummaryExampleTable, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
data_summary_table(cylByYearSummaryExample)
```
### Output the plot
```{r cylByYearSummaryExamplePlot, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
data_summary_plot(cylByYearSummaryExample)
```
### Generate a knitr friendly summary table
```{r cylByYearSummaryExampleKnitrTable, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE}
make_kable_output(cylByYearSummaryExample)
```
### Generate knitr friendly output
```{r cylByYearSummaryExampleComplete, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7, fig.align = 'center', fig.cap = paste("Stacked barplot of ", label(mpg$cyl), " by ", label(mpg$year), ".", sep = "")}
make_complete_output(cylByYearSummaryExample)
```
:::
## Categorical By By
::: {.panel-tabset .tabset-fade .tabset-pills}
For a categorical variable with two or more by variables, we need to specify <b>x</b>, the <b>by</b> variables as a character string, and the <b>data</b>.
```{r cylByYearByPartySummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
cylByYearByPartySummaryExample <- data_summary(x = "cyl", by = c("year", "party"), data = mpg)
```
### Show method to output table and plot
```{r cylByYearByPartySummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
show(cylByYearByPartySummaryExample)
```
### Output the summary table
```{r cylByYearByPartySummaryExampleTable, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
data_summary_table(cylByYearByPartySummaryExample)
```
### Output the plot
```{r cylByYearByPartySummaryExamplePlot, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
data_summary_plot(cylByYearByPartySummaryExample)
```
### Generate a knitr friendly summary table
```{r cylByYearByPartySummaryExampleKnitrTable, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE}
make_kable_output(cylByYearByPartySummaryExample)
```
### Generate knitr friendly output
```{r cylByYearByPartySummaryExampleComplete, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7, fig.align = 'center', fig.cap = paste("Stacked barplot of ", label(mpg$cyl), " by ", label(mpg$year), " by ", label(mpg$party), ".", sep = "")}
make_complete_output(cylByYearByPartySummaryExample)
```
:::
## Continuous
::: {.panel-tabset .tabset-fade .tabset-pills}
For a continuous variable <b>x</b>, we only need to specify <b>x</b> and the <b>data</b>.
```{r ctySummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
ctySummaryExample <- data_summary(x = "cty", data = mpg)
```
### Show method to output table and plot
```{r ctySummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
show(ctySummaryExample)
```
### Output the summary table
```{r ctySummaryExampleTable, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
data_summary_table(ctySummaryExample)
```
### Output the plot
```{r ctySummaryExamplePlot, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
data_summary_plot(ctySummaryExample)
```
### Generate knitr friendly summary table
```{r ctySummaryExampleKnitrTable, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
make_kable_output(ctySummaryExample)
```
### Generate knitr friendly output
```{r ctySummaryExampleComplete, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7, fig.align = 'center', fig.cap = paste("Stacked barplot of ", label(mpg$cty), ".", sep = "")}
make_complete_output(ctySummaryExample)
```
:::
## Continuous By
::: {.panel-tabset .tabset-fade .tabset-pills}
For a continuous variable with by, we need to specify <b>x</b>, a <b>by</b> variable, and the <b>data</b>.
```{r ctyByCylSummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
ctyByCylSummaryExample <- data_summary(x = "cty", by = "cyl", data = mpg)
```
### Show method to output table and plot
```{r ctyByCylSummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
show(ctyByCylSummaryExample)
```
### Output the summary table
```{r ctyByCylSummaryExampleTable, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
data_summary_table(ctyByCylSummaryExample)
```
### Output the plot
```{r ctyByCylSummaryExamplePlot, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
data_summary_plot(ctyByCylSummaryExample)
```
### Generate a knitr friendly summary table
```{r ctyByCylSummaryExampleKnitrTable, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE}
make_kable_output(ctyByCylSummaryExample)
```
### Generate knitr friendly output
```{r ctyByCylSummaryExampleComplete, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7, fig.align = 'center', fig.cap = paste("Stacked barplot of ", label(mpg$cty), " by ", label(mpg$cyl), ".", sep = "")}
make_complete_output(ctyByCylSummaryExample)
```
:::
## Continuous By By
::: {.panel-tabset .tabset-fade .tabset-pills}
For a continuous variable with two or more by variables, we need to specify <b>x</b>, the <b>by</b> variables as a character string, and the <b>data</b>.
```{r ctyByCylByYearSummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
ctyByCylByYearSummaryExample <- data_summary(x = "cty", by = c("cyl", "year"), data = mpg)
```
### Show method to output table and plot
```{r ctyByCylByYearSummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
show(ctyByCylByYearSummaryExample)
```
### Output the summary table
```{r ctyByCylByYearSummaryExampleTable, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
data_summary_table(ctyByCylByYearSummaryExample)
```
### Output the plot
```{r ctyByCylByYearSummaryExamplePlot, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7}
data_summary_plot(ctyByCylByYearSummaryExample)
```
### Generate a knitr friendly summary table
```{r ctyByCylByYearSummaryExampleKnitrTable, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE}
make_kable_output(ctyByCylByYearSummaryExample)
```
### Generate knitr friendly output
```{r ctyByCylByYearSummaryExampleComplete, eval = TRUE, echo = TRUE, results = 'asis', warning = FALSE, message = FALSE, fig.width = 7, fig.asp = 0.7, fig.align = 'center', fig.cap = paste("Stacked barplot of ", label(mpg$cty), " by ", label(mpg$cyl), " by ", label(mpg$year), ".", sep = "")}
make_complete_output(ctyByCylByYearSummaryExample)
```
:::
## Date
::: {.panel-tabset .tabset-fade .tabset-pills}
For a date variable <b>x</b>, we need to specify <b>x</b>, the <b>data</b>, and <b>difftime_units</b>.
```{r dpSummaryExample, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}
dpSummaryExample <- data_summary(x = "dp", data = mpg[which(mpg$dp != "1000-05-02" | is.na(mpg$dp)), ], difftime_units = "weeks")
```
### Show method to output table and plot
```{r dpSummaryExampleShow, eval = TRUE, echo = TRUE, results = TRUE, warning = FALSE, message = FALSE}