/
binning.R
1596 lines (1424 loc) · 54.5 KB
/
binning.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
#' Binning the Numeric Data
#'
#' @description The binning() converts a numeric variable to a categorization variable.
#'
#' @details This function is useful when used with the mutate/transmute
#' function of the dplyr package.
#'
#' See vignette("transformation") for an introduction to these concepts.
#'
#' @param x numeric. numeric vector for binning.
#' @param nbins integer. number of intervals(bins). required. if missing, nclass.Sturges is used.
#' @param type character. binning method. Choose from "quantile", "equal", "pretty", "kmeans" and "bclust".
#' The "quantile" sets breaks with quantiles of the same interval.
#' The "equal" sets breaks at the same interval.
#' The "pretty" chooses a number of breaks not necessarily equal
#' to nbins using base::pretty function.
#' The "kmeans" uses stats::kmeans function to generate the breaks.
#' The "bclust" uses e1071::bclust function to generate the breaks using bagged clustering.
#' "kmeans" and "bclust" was implemented by classInt::classIntervals() function.
#' @param ordered logical. whether to build an ordered factor or not.
#' @param labels character. the label names to use for each of the bins.
#' @param approxy.lab logical. If TRUE, large number breaks are approximated to pretty numbers.
#' If FALSE, the original breaks obtained by type are used.
#' @return An object of bins class.
#' Attributes of bins class is as follows.
#' \itemize{
#' \item class : "bins"
#' \item type : binning type, "quantile", "equal", "pretty", "kmeans", "bclust".
#' \item breaks : breaks for binning. the number of intervals into which x is to be cut.
#' \item levels : levels of binned value.
#' \item raw : raw data, numeric vector corresponding to x argument.
#' }
#' @seealso \code{\link{binning_by}}, \code{\link{print.bins}}, \code{\link{summary.bins}},
#' \code{\link{plot.bins}}.
#' @export
#' @examples
#' \donttest{
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 20), "platelets"] <- NA
#'
#' # Binning the platelets variable. default type argument is "quantile"
#' bin <- binning(heartfailure2$platelets)
#' # Print bins class object
#' bin
#'
#' # Using labels argument
#' bin <- binning(heartfailure2$platelets, nbins = 4,
#' labels = c("LQ1", "UQ1", "LQ3", "UQ3"))
#' bin
#'
#' # Using another type argument
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "equal")
#' bin
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "pretty")
#' bin
#' # "kmeans" and "bclust" was implemented by classInt::classIntervals() function.
#' # So, you must install classInt package.
#' if (requireNamespace("classInt", quietly = TRUE)) {
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "kmeans")
#' bin
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "bclust")
#' bin
#' } else {
#' cat("If you want to use this feature, you need to install the 'classInt' package.\n")
#' }
#'
#' x <- sample(1:1000, size = 50) * 12345679
#' bin <- binning(x)
#' bin
#' bin <- binning(x, approxy.lab = FALSE)
#' bin
#'
#' # extract binned results
#' extract(bin)
#'
#' # -------------------------
#' # Using pipes & dplyr
#' # -------------------------
#' library(dplyr)
#'
#' # Compare binned frequency by death_event
#' heartfailure2 %>%
#' mutate(platelets_bin = binning(heartfailure2$platelets) %>%
#' extract()) %>%
#' group_by(death_event, platelets_bin) %>%
#' summarise(freq = n(), .groups = "drop") %>%
#' arrange(desc(freq)) %>%
#' head(10)
#' }
#'
#' @importFrom grDevices nclass.Sturges
#' @importFrom stats na.omit quantile
#' @export
binning <- function(x, nbins,
type = c("quantile", "equal", "pretty", "kmeans", "bclust"),
ordered = TRUE, labels = NULL, approxy.lab = TRUE) {
if (is.factor(x))
stop("x is categorical value")
if (!is.numeric(x))
stop("x is not numeric value")
if (missing(nbins))
nbins <- nclass.Sturges(x)
if (nbins < 2)
stop("nbins less than 2")
nuniq <- length(unique(x))
if (nuniq == 1)
stop("There is only one unique value of the x.")
type <- match.arg(type)
if (nbins > nuniq) {
msg <- "nbins is greater than the number of unique values for x.
So we assign 'nbins' the number of unique values of x."
warning(msg)
nbins <- nuniq
}
if (nbins == nuniq) {
msg <- "The type argument is replaced by equal because nbins has the
same number of unique values for x."
warning(msg)
nbins <- nuniq
sorted <- sort(unique(x))
interval <- diff(sorted)
breaks <- c(min(sorted) - interval[1] / 2,
sorted[1:(nbins - 1)] + interval / 2,
max(sorted) + interval[length(interval)] / 2)
type <- "equal"
} else if (type == "quantile") {
breaks <- quantile(x, probs = seq(0, 1, by = 1 / nbins),
na.rm = TRUE, type = 8)
breaks <- unique(breaks)
breaks[1] <- min(x, na.rm = TRUE)
breaks[length(breaks)] <- max(x, na.rm = TRUE)
names(breaks) <- NULL
} else if (type == "equal") {
breaks <- seq(min(x, na.rm = TRUE), max(x, na.rm = TRUE),
length.out = (nbins + 1))
} else if (type == "pretty") {
breaks <- pretty(x = x, n = nbins)
} else {
if (!requireNamespace("classInt", quietly = TRUE)) {
warning("Package \"classInt\" needed for this function to work. Please install it.",
call. = FALSE)
return(NULL)
}
xx <- na.omit(x)
if (type == "bclust") {
ci <- classInt::classIntervals(var = xx, n = nbins, style = type, verbose = FALSE)
} else {
ci <- classInt::classIntervals(var = xx, n = nbins, style = type)
}
breaks <- ci$brks
}
breaks <- unique(breaks)
dig.lab <- breaks %>%
nchar() %>%
max() %>%
min(7)
fct <- cut(x, breaks = breaks, labels = labels, include.lowest = TRUE,
dig.lab = dig.lab)
if (is.null(labels)) {
pretty.lab <- levels(fct) %>%
gsub("[(\\[]|]", "", .) %>%
strsplit(",") %>%
sapply(c) %>%
as.numeric() %>%
unique()
pretty.lab[1] <- min(x, na.rm = TRUE)
pretty.lab[length(pretty.lab)] <- max(x, na.rm = TRUE)
if (approxy.lab) {
if (!all(pretty.lab == breaks)) {
fct <- cut(x, breaks = pretty.lab, labels = levels(fct), include.lowest = TRUE)
}
} else {
if (!all(pretty.lab == breaks)) {
lab <- NULL
for (i in 2:length(breaks)) {
lab <- c(lab, paste0("(", prettyNum(breaks[i - 1]), ",", prettyNum(breaks[i]), "]"))
}
lab[1] <- sub("^\\(", "[", lab[1])
levels(fct) <- lab
}
}
}
if (ordered == TRUE)
fct <- ordered(fct, levels = levels(fct))
results <- fct
attr(results, "type") <- type
attr(results, "breaks") <- breaks
attr(results, "levels") <- levels(fct)
attr(results, "raw") <- x
class(results) <- append("bins", class(results))
results
}
#' Summarizing Binned Variable
#'
#' @description summary method for "bins" and "optimal_bins".
#' @param object an object of "bins" and "optimal_bins",
#' usually, a result of a call to binning().
#' @param ... further arguments to be passed from or to other methods.
#' @details
#' print.bins() prints the information of "bins" and "optimal_bins" objects nicely.
#' This includes frequency of bins, binned type, and number of bins.
#' summary.bins() returns data.frame including frequency and relative frequency for each levels(bins).
#'
#' See vignette("transformation") for an introduction to these concepts.
#'
#' @return
#' The function summary.bins() computes and returns a data.frame of summary statistics of the
#' binned given in object. Variables of data frame is as follows.
#' \itemize{
#' \item levels : levels of factor.
#' \item freq : frequency of levels.
#' \item rate : relative frequency of levels. it is not percentage.
#' }
#' @seealso \code{\link{binning}}
#' @examples
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 20), "platelets"] <- NA
#'
#' # Binning the platelets variable. default type argument is "quantile"
#' bin <- binning(heartfailure2$platelets)
#'
#' # Print bins class object
#' bin
#'
#' # Summarize bins class object
#' summary(bin)
#'
#' @method summary bins
#' @export
summary.bins <- function(object, ...) {
tab <- table(object, exclude = NULL)
data.frame(levels = names(tab),
freq = as.numeric(tab),
rate = as.numeric(tab) / length(object))
}
#' @param x an object of class "bins" and "optimal_bins",
#' usually, a result of a call to binning().
#' @param ... further arguments passed to or from other methods.
#' @rdname summary.bins
#' @method print bins
#' @export
print.bins <- function(x, ...) {
cat("binned type: ", attr(x, "type"), "\n", sep = "")
cat("number of bins: ", length(levels(x)), "\n", sep = "")
print(table(x, exclude = NULL))
}
#' Visualize Distribution for a "bins" object
#'
#' @description
#' Visualize two plots on a single screen.
#' The plot at the top is a histogram representing the frequency of the level.
#' The plot at the bottom is a bar chart representing the frequency of the level.
#'
#' @details The base_family is selected from "Roboto Condensed", "Liberation Sans Narrow",
#' "NanumSquare", "Noto Sans Korean". If you want to use a different font,
#' use it after loading the Google font with import_google_font().
#'
#' @param x an object of class "bins", usually, a result of a call to binning().
#' @param typographic logical. Whether to apply focuses on typographic elements to ggplot2 visualization.
#' The default is TRUE. if TRUE provides a base theme that focuses on typographic elements using hrbrthemes package.
#' @param base_family character. The name of the base font family to use
#' for the visualization. If not specified, the font defined in dlookr is applied. (See details)
#' @param ... arguments to be passed to methods, such as graphical parameters (see par).
#' @return An object of gtable class.
#' @seealso \code{\link{binning}}, \code{\link{print.bins}}, \code{\link{summary.bins}}.
#' @examples
#' # Generate data for the example
#' \donttest{
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 20), "platelets"] <- NA
#'
#' # Binning the platelets variable. default type argument is "quantile"
#' bin <- binning(heartfailure2$platelets, nbins = 5)
#' plot(bin)
#'
#' # Using another type arguments
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "equal")
#' plot(bin)
#'
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "pretty")
#' plot(bin)
#'
#' # "kmeans" and "bclust" was implemented by classInt::classIntervals() function.
#' # So, you must install classInt package.
#' if (requireNamespace("classInt", quietly = TRUE)) {
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "kmeans")
#' plot(bin)
#'
#' bin <- binning(heartfailure2$platelets, nbins = 5, type = "bclust")
#' plot(bin)
#' }
#' }
#'
#' @export
#' @method plot bins
#' @importFrom gridExtra grid.arrange
#' @import hrbrthemes
#' @import ggplot2
plot.bins <- function(x, typographic = TRUE, base_family = NULL, ...) {
brks <- attr(x, "breaks")
type <- attr(x, "type")
levels <- attr(x, "levels")
bins <- factor(x, levels = levels(x))
n <- seq(levels)
deltas <- diff(brks)
height <- table(bins) / deltas / length(bins)
data_top <- data.frame(x_start = brks[-length(brks)], x_end = brks[-1],
height = height)
p_top <- data_top %>%
ggplot() +
geom_rect(aes(xmin = x_start, xmax = x_end,
ymin = 0, ymax = height),
fill = "#69b3a2", alpha = 0.8, color = "black") +
xlim(min(brks), max(brks)) +
labs(title = sprintf("Density of original data using '%s' method", type),
y = "Density") +
theme_grey(base_family = base_family)
if (typographic) {
p_top <- p_top +
theme_typographic(base_family)
}
data_bottom <- data.frame(bins = seq(levels), freq = as.integer(table(bins)) / length(bins))
p_bottom <- data_bottom %>%
ggplot(aes(x = bins, y = freq)) +
geom_bar(stat = "identity", fill = "#404080", width = 0.8,
alpha = 0.8, color = "black") +
labs(title = sprintf("Relative frequency by bins using '%s' method", type),
x = "", y = "Relative Frequency") +
scale_x_continuous(breaks = seq(levels),
labels = levels,
limits = c(0.5, length(levels) + 0.5)) +
theme_grey(base_family = base_family)
if (typographic) {
p_bottom <- p_bottom +
theme_typographic(base_family) +
theme(plot.margin = margin(5, 20, 10, 20))
}
p_bottom <- p_bottom +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
suppressWarnings(gridExtra::grid.arrange(p_top, p_bottom, nrow = 2, ncol = 1))
}
#' Optimal Binning for Scoring Modeling
#'
#' @description The binning_by() finding intervals for numerical variable
#' using optical binning. Optimal binning categorizes a numeric characteristic
#' into bins for ulterior usage in scoring modeling.
#'
#' @details This function is useful when used with the mutate/transmute
#' function of the dplyr package. And this function is implemented using
#' smbinning() function of smbinning package.
#'
#' @section attributes of "optimal_bins" class:
#' Attributes of the "optimal_bins" class that is as follows.
#' \itemize{
#' \item class : "optimal_bins".
#' \item levels : character. factor or ordered factor levels
#' \item type : character. binning method
#' \item breaks : numeric. breaks for binning
#' \item raw : numeric. before the binned the raw data
#' \item ivtable : data.frame. information value table
#' \item iv : numeric. information value
#' \item target : integer. binary response variable
#' }
#'
#' See vignette("transformation") for an introduction to these concepts.
#'
#' @param .data a data frame.
#' @param y character. name of binary response variable(0, 1).
#' The variable must contain only the integers 0 and 1 as element.
#' However, in the case of factor having two levels, it is performed while type conversion is performed in the calculation process.
#' @param x character. name of continuous characteristic variable. At least 5 different values. and Inf is not allowed.
#' @param p numeric. percentage of records per bin. Default 5\% (0.05).
#' This parameter only accepts values greater that 0.00 (0\%) and lower than 0.50 (50\%).
#' @param ordered logical. whether to build an ordered factor or not.
#' @param labels character. the label names to use for each of the bins.
#' @return an object of "optimal_bins" class.
#' Attributes of "optimal_bins" class is as follows.
#' \itemize{
#' \item class : "optimal_bins".
#' \item type : binning type, "optimal".
#' \item breaks : numeric. the number of intervals into which x is to be cut.
#' \item levels : character. levels of binned value.
#' \item raw : numeric. raw data, x argument value.
#' \item ivtable : data.frame. information value table.
#' \item iv : numeric. information value.
#' \item target : integer. binary response variable.
#' }
#' @seealso \code{\link{binning}}, \code{\link{summary.optimal_bins}}, \code{\link{plot.optimal_bins}}.
#' @examples
#' library(dplyr)
#'
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 5), "creatinine"] <- NA
#'
#' # optimal binning using character
#' bin <- binning_by(heartfailure2, "death_event", "creatinine")
#'
#' # optimal binning using name
#' bin <- binning_by(heartfailure2, death_event, creatinine)
#' bin
#'
#' @export
#' @importFrom tibble is_tibble
#' @importFrom tidyselect vars_select
#' @importFrom rlang quos
#' @import dplyr
binning_by <- function(.data, y, x, p = 0.05, ordered = TRUE, labels = NULL) {
if (!requireNamespace("partykit", quietly = TRUE)) {
warning("Package \"partykit\" needed for this function to work. Please install it.",
call. = FALSE)
return(NULL)
}
y <- tidyselect::vars_select(names(.data), !! enquo(y))
x <- tidyselect::vars_select(names(.data), !! enquo(x))
if (tibble::is_tibble(.data)) {
.data <- as.data.frame(.data)
}
uniq_y <- length(unique(.data[, y]))
type_y <- class(.data[, y])[1]
type_x <- class(.data[, x])[1]
if (!is.data.frame(.data))
stop("Data is not a data.frame.")
if (!type_x %in% c("integer", "numeric"))
stop("x is not numeric value.")
if (uniq_y != 2) {
stop("The number of levels of the y variable is not 2.")
}
if (type_y %in% c("integer", "numeric")) {
if (!all(unique(.data[, y]) %in% c(0, 1))) {
stop("If y is a numeric variable, it can have only values of 0 and 1. (1: positive, 0: Negative)")
}
}
if (type_y %in% c("factor", "ordered")) {
yval <- levels(.data[, y])
.data[, y] <- as.integer(.data[, y]) - 1
msg <- sprintf("'%s' changed to 1 (positive) and '%s' changed to 0 (negative).", yval[2], yval[1])
warning(paste("The factor y has been changed to a numeric vector consisting of 0 and 1.", msg, sep = "\n"))
}
if (type_y %in% c("character")) {
yval <- levels(factor(.data[, y]))
.data[, y] <- as.integer(factor(.data[, y]))- 1
msg <- sprintf("'%s' changed to 1 (positive) and '%s' changed to 0 (negative).", yval[2], yval[1])
warning(paste("The character y has been changed to a numeric vector consisting of 0 and 1.", msg, sep = "\n"))
}
if (any(is.infinite(.data[, x])))
stop("x with an Inf. Replace by NA. or Remove the Inf.")
if (p <= 0 | p > 0.5)
stop("p must be, 0 < p <= 0.5")
if (length(unique(.data[, x])) < 5)
stop("x must be number of unique values greater then 4.")
ctree <- partykit::ctree(
formula(paste("`", y,"`", " ~ ", "`", x, "`", sep = "")),
data = .data, na.action = na.exclude,
control = partykit::ctree_control(
minbucket = ceiling(round(p * nrow(.data)))
)
)
bins <- partykit::width(ctree)
if (bins < 2) {
msg <- "No significant splits"
results <- msg
class(results) <- append("optimal_bins", class(results))
warning(msg, "\n")
return(results)
}
cutvct <- seq(ctree) %>%
map_dbl(function(x) {
breaks <- ctree[x]$node$split$breaks
ifelse(is.null(breaks), NA, breaks)
}) %>%
sort()
min_max <- range(.data[, x], na.rm = TRUE)
cufoff <- c(min_max[1], cutvct, min_max[2])
breaks <- cufoff
tab <- table(breaks)
dup <- as.numeric(names(tab)[which(tab == 2)])
if (length(dup) > 0) {
breaks <- unique(c(ifelse(min(breaks) == dup, dup - 1, dup + 1), breaks))
}
fct <- cut(.data[, x], breaks = breaks, labels = labels, include.lowest = TRUE)
if (ordered == TRUE)
fct <- ordered(fct)
perf <- performance_bin(.data[, y], fct)
results <- fct
attr(results, "type") <- "optimal"
attr(results, "breaks") <- breaks
attr(results, "levels") <- levels(fct)
attr(results, "raw") <- .data[, x]
class(results) <- append("bins", class(results))
attr(results, "performance") <- perf
attr(results, "target") <- .data[, y]
class(results) <- append("optimal_bins", class(results))
results
}
#' Summarizing Performance for Optimal Bins
#'
#' @description summary method for "optimal_bins". summary metrics to evaluate the performance
#' of binomial classification model.
#' @param object an object of class "optimal_bins", usually, a result of a call to binning_by().
#' @param ... further arguments to be passed from or to other methods.
#' @details
#' print() to print only binning table information of "optimal_bins" objects.
#' summary.performance_bin() includes general metrics and result of significance tests life follows.:
#' \itemize{
#' \item Binning Table : Metrics by bins.
#' \itemize{
#' \item CntRec, CntPos, CntNeg, RatePos, RateNeg, Odds, WoE, IV, JSD, AUC.
#' }
#' \item General Metrics.
#' \itemize{
#' \item Gini index.
#' \item Jeffrey's Information Value.
#' \item Jensen-Shannon Divergence.
#' \item Kolmogorov-Smirnov Statistics.
#' \item Herfindahl-Hirschman Index.
#' \item normalized Herfindahl-Hirschman Index.
#' \item Cramer's V Statistics.
#' }
#' \item Table of Significance Tests.
#' }
#' @return NULL.
#' @seealso \code{\link{binning_by}}, \code{\link{plot.optimal_bins}}
#' @examples
#' library(dplyr)
#'
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 5), "creatinine"] <- NA
#'
#' # optimal binning
#' bin <- binning_by(heartfailure2, "death_event", "creatinine")
#' bin
#'
#' # summary optimal_bins class
#' summary(bin)
#'
#' # performance table
#' attr(bin, "performance")
#'
#' # extract binned results
#' if (!is.null(bin)) {
#' extract(bin) %>%
#' head(20)
#' }
#'
#' @method summary optimal_bins
#' @export
summary.optimal_bins <- function(object, ...) {
perf <- attr(object, "performance")
summary(perf)
}
#' Visualize Distribution for an "optimal_bins" Object
#'
#' @description
#' It generates plots for understand distribution, frequency, bad rate, and weight of evidence using optimal_bins.
#'
#' See vignette("transformation") for an introduction to these concepts.
#'
#' @details The base_family is selected from "Roboto Condensed", "Liberation Sans Narrow",
#' "NanumSquare", "Noto Sans Korean". If you want to use a different font,
#' use it after loading the Google font with import_google_font().
#'
#' @param x an object of class "optimal_bins", usually, a result of a call to binning_by().
#' @param type character. options for visualization. Distribution ("dist"), Relateive Frequency ("freq"),
#' Positive Rate ("posrate"), and Weight of Evidence ("WoE"). and default "all" draw all plot.
#' @param typographic logical. Whether to apply focuses on typographic elements to ggplot2 visualization.
#' The default is TRUE. if TRUE provides a base theme that focuses on typographic elements using hrbrthemes package.
#' @param base_family character. The name of the base font family to use
#' for the visualization. If not specified, the font defined in dlookr is applied. (See details)
#' @param rotate_angle integer. specifies the rotation angle of the x-axis label.
#' This is useful when the x-axis labels are long and overlap.
#' The default is 0 to not rotate the label.
#' @param ... further arguments to be passed from or to other methods.
#' @return An object of gtable class.
#' @seealso \code{\link{binning_by}}, \code{\link{summary.optimal_bins}}
#' @examples
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 5), "creatinine"] <- NA
#'
#' # optimal binning using binning_by()
#' bin <- binning_by(heartfailure2, "death_event", "creatinine")
#'
#' if (!is.null(bin)) {
#' # visualize all information for optimal_bins class
#' plot(bin)
#'
#' # rotate the x-axis labels by 45 degrees so that they do not overlap.
#' plot(bin, rotate_angle = 45)
#'
#' # visualize WoE information for optimal_bins class
#' plot(bin, type = "WoE")
#'
#' # visualize all information with typographic
#' plot(bin)
#' }
#'
#' @import ggplot2
#' @import hrbrthemes
#' @importFrom gridExtra grid.arrange
#' @export
#' @method plot optimal_bins
plot.optimal_bins <- function(x, type = c("all", "dist", "freq", "posrate", "WoE"),
typographic = TRUE, base_family = NULL,
rotate_angle = 0, ...) {
if (is.character(x)) {
cat("binn is the optimal_bins object that can not be binned : \n",
x, "\n", sep = "")
} else {
ivt <- attr(x, "performance")
type <- match.arg(type)
if (type %in% c("all", "dist")) {
p_dist <- data.frame(indicator = attr(x, "raw"), target = as.character(attr(x, "target"))) %>%
ggplot(aes(x = target, y= indicator, group = target)) +
geom_boxplot(fill = "slategrey", color = "darkslategrey", width = 0.3) +
coord_flip() +
ggtitle("Distribution of target") +
theme_grey(base_family = base_family) +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (typographic) {
p_dist <- p_dist +
theme_typographic(base_family) +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (type %in% c("all")) {
p_dist <- p_dist +
theme(axis.title.y = element_text(size = 12),
axis.title.x = element_text(size = 12),
plot.margin = margin(10, 10, 10, 10))
}
}
}
if (type %in% c("all", "freq")) {
p_freq <- ivt %>%
filter(!Bin %in% "Total") %>%
mutate(Bin = factor(Bin, levels = attr(x, "levels"))) %>%
mutate(PctRec = round(CntRec / sum(CntRec) * 100, 1)) %>%
mutate(add_pos = max(PctRec) * 0.1) %>%
ggplot(aes(x = Bin, y = PctRec, fill = Bin)) +
geom_bar(stat = "identity", width = 0.5) +
scale_fill_brewer(na.value = "grey") +
geom_text(aes(label = PctRec, y = PctRec + add_pos)) +
xlab("") +
ylab("") +
ggtitle("Percentage of frequency") +
theme_grey(base_family = base_family) +
theme(legend.position = "none") +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (typographic) {
p_freq <- p_freq +
theme_typographic(base_family) +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (type %in% c("all")) {
p_freq <- p_freq +
theme(legend.position = "none",
plot.margin = margin(10, 10, 10, 10))
}
}
}
if (type %in% c("all", "posrate")) {
p_badrate <- ivt %>%
filter(!Bin %in% "Total") %>%
mutate(Bin = factor(Bin, levels = attr(x, "levels"))) %>%
mutate(PctPos = round(RatePos * 100, 1)) %>%
mutate(add_pos = max(PctPos) * 0.1) %>%
ggplot(aes(x = Bin, y = PctPos, fill = Bin)) +
geom_bar(stat = "identity", width = 0.5) +
scale_fill_brewer(na.value = "grey") +
geom_text(aes(label = PctPos, y = PctPos + add_pos)) +
xlab("") +
ylab("") +
ggtitle("Percentage of positive") +
theme_grey(base_family = base_family) +
theme(legend.position = "none") +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (typographic) {
p_badrate <- p_badrate +
theme_typographic(base_family) +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (type %in% c("all")) {
p_badrate <- p_badrate +
theme(legend.position = "none",
plot.margin = margin(10, 10, 10, 10))
}
}
}
if (type %in% c("all", "WoE")) {
p_woe <- ivt %>%
filter(!Bin %in% "Total") %>%
mutate(Bin = factor(Bin, levels = attr(x, "levels"))) %>%
mutate(add_pos = max(WoE) * 0.1) %>%
ggplot(aes(x = Bin, y = WoE, fill = Bin)) +
geom_bar(stat = "identity", width = 0.5) +
scale_fill_brewer(na.value = "grey") +
geom_text(aes(label = round(WoE, 2), y = WoE + add_pos)) +
xlab("") +
ylab("") +
ggtitle("Weight of Evidence") +
theme_grey(base_family = base_family) +
theme(legend.position = "none") +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (typographic) {
p_woe <- p_woe +
theme_typographic(base_family) +
theme(axis.text.x = element_text(angle = rotate_angle,
vjust = 0.5, hjust = 0.5))
if (type %in% c("all")) {
p_woe <- p_woe +
theme(legend.position = "none",
plot.margin = margin(10, 10, 10, 10))
}
}
}
if (type %in% c("all")) {
p_dist <- p_dist +
theme(plot.title = element_text(size = 15))
p_freq <- p_freq +
theme(plot.title = element_text(size = 15))
p_badrate <- p_badrate +
theme(plot.title = element_text(size = 15))
p_woe <- p_woe +
theme(plot.title = element_text(size = 15))
suppressWarnings(gridExtra::grid.arrange(p_dist, p_freq, p_badrate, p_woe, nrow = 2, ncol = 2))
} else if (type %in% c("dist")) {
suppressWarnings(p_dist)
} else if (type %in% c("freq")) {
suppressWarnings(p_freq)
} else if (type %in% c("posrate")) {
suppressWarnings(p_badrate)
} else if (type %in% c("WoE")) {
suppressWarnings(p_woe)
}
}
}
#' @rdname extract.bins
#' @export
extract <- function(x) {
UseMethod("extract", x)
}
#' Extract bins from "bins"
#'
#' @description The extract() extract binned variable from "bins", "optimal_bins" class object.
#'
#' @details The "bins" and "optimal_bins" class objects use the summary() and plot() functions to diagnose
#' the performance of binned results. This function is used to extract the binned result if you are satisfied
#' with the result.
#'
#' @param x a bins class or optimal_bins class.
#'
#' @return factor.
#' @seealso \code{\link{binning}}, \code{\link{binning_by}}.
#' @export
#' @examples
#' library(dplyr)
#'
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#' heartfailure2[sample(seq(NROW(heartfailure2)), 5), "creatinine"] <- NA
#'
#' # optimal binning using binning_by()
#' bin <- binning_by(heartfailure2, "death_event", "creatinine")
#' bin
#'
#' if (!is.null(bin)) {
#' # extract binning result
#' extract(bin) %>%
#' head(20)
#' }
#'
#' @export
#' @method extract bins
extract.bins <- function(x) {
object <- unclass(x)
idx <- as.integer(object)
levels <- attr(object,"levels")
raw <- factor(levels[idx], levels = levels)
class(raw) <- grep("bins", class(x), invert = TRUE, value = TRUE)
raw
}
#' Diagnose Performance Binned Variable
#'
#' @description The performance_bin() calculates metrics to evaluate the performance of binned variable for
#' binomial classification model.
#'
#' @details This function is useful when used with the mutate/transmute
#' function of the dplyr package.
#'
#' @param y character or numeric, integer, factor. a binary response variable (0, 1).
#' The variable must contain only the integers 0 and 1 as element.
#' However, in the case of factor/character having two levels, it is performed while type conversion is performed in the calculation process.
#' @param x integer or factor, character. At least 2 different values. and Inf is not allowed.
#' @param na.rm logical. a logical indicating whether missing values should be removed.
#' @return an object of "performance_bin" class. vaue of data.frame is as follows.
#' \itemize{
#' \item Bin : character. bins.
#' \item CntRec : integer. frequency by bins.
#' \item CntPos : integer. frequency of positive by bins.
#' \item CntNeg : integer. frequency of negative by bins.
#' \item CntCumPos : integer. cumulate frequency of positive by bins.
#' \item CntCumNeg : integer. cumulate frequency of negative by bins.
#' \item RatePos : integer. relative frequency of positive by bins.
#' \item RateNeg : integer. relative frequency of negative by bins.
#' \item RateCumPos : numeric. cumulate relative frequency of positive by bins.
#' \item RateCumNeg : numeric. cumulate relative frequency of negative by bins.
#' \item Odds : numeric. odd ratio.
#' \item LnOdds : numeric. loged odd ratio.
#' \item WoE : numeric. weight of evidence.
#' \item IV : numeric. Jeffrey's Information Value.
#' \item JSD : numeric. Jensen-Shannon Divergence.
#' \item AUC : numeric. AUC. area under curve.
#' }
#' Attributes of "performance_bin" class is as follows.
#' \itemize{
#' \item names : character. variable name of data.frame with "Binning Table".
#' \item class : character. name of class. "performance_bin" "data.frame".
#' \item row.names : character. row name of data.frame with "Binning Table".
#' \item IV : numeric. Jeffrey's Information Value.
#' \item JSD : numeric. Jensen-Shannon Divergence.
#' \item KS : numeric. Kolmogorov-Smirnov Statistics.
#' \item gini : numeric. Gini index.
#' \item HHI : numeric. Herfindahl-Hirschman Index.
#' \item HHI_norm : numeric.normalized Herfindahl-Hirschman Index.
#' \item Cramer_V : numeric. Cramer's V Statistics.
#' \item chisq_test : data.frame. table of significance tests. name is as follows.
#' \itemize{
#' \item Bin A : character. first bins.
#' \item Bin B : character. second bins.
#' \item statistics : numeric. statistics of Chi-square test.
#' \item p_value : numeric. p-value of Chi-square test.
#' }
#' }
#' @seealso \code{\link{summary.performance_bin}}, \code{\link{plot.performance_bin}}, \code{\link{binning_by}}.
#' @examples
#' \donttest{
#' # Generate data for the example
#' heartfailure2 <- heartfailure
#'
#' set.seed(123)
#' heartfailure2[sample(seq(NROW(heartfailure2)), 5), "creatinine"] <- NA
#'
#' # Change the target variable to 0(negative) and 1(positive).
#' heartfailure2$death_event_2 <- ifelse(heartfailure2$death_event %in% "Yes", 1, 0)
#'
#' # Binnig from creatinine to platelets_bin.
#' breaks <- c(0, 1, 2, 10)
#' heartfailure2$creatinine_bin <- cut(heartfailure2$creatinine, breaks)
#'
#' # Diagnose performance binned variable
#' perf <- performance_bin(heartfailure2$death_event_2, heartfailure2$creatinine_bin)
#' perf
#' summary(perf)
#'
#' plot(perf)
#'
#' # Diagnose performance binned variable without NA
#' perf <- performance_bin(heartfailure2$death_event_2, heartfailure2$creatinine_bin, na.rm = TRUE)
#' perf
#' summary(perf)
#'
#' plot(perf)
#' }
#'
#' @export
#' @import dplyr
#'
performance_bin <- function (y, x, na.rm = FALSE) {
uniq_y <- length(unique(y))
type_y <- class(y)[1]
type_x <- class(x)[1]
if (uniq_y != 2) {
stop("The number of levels of the y variable is not 2.")
}
if (type_y %in% c("integer", "numeric")) {
if (!all(unique(y) %in% c(0, 1))) {
stop("If y is a numeric variable, it can have only values of 0 and 1. (1: positive, 0: Negative)")
}
}
if (type_y %in% c("factor", "ordered")) {
yval <- levels(y)
y <- as.integer(y) - 1
msg <- sprintf("'%s' changed to 1 (positive) and '%s' changed to 0 (negative).", yval[2], yval[1])
warning(paste("The factor y has been changed to a numeric vector consisting of 0 and 1.", msg, sep = "\n"))
}
if (type_y %in% c("character")) {
yval <- levels(factor(y))
y <- as.integer(factor(y))- 1
msg <- sprintf("'%s' changed to 1 (positive) and '%s' changed to 0 (negative).", yval[2], yval[1])
warning(paste("The character y has been changed to a numeric vector consisting of 0 and 1.", msg, sep = "\n"))
}