-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathDesc.R
3843 lines (3296 loc) · 114 KB
/
Desc.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
ChisqWarning <- function(){
cat(cli::col_red("\nWarning message:\n Exp. counts < 5: Chi-squared approx. may be incorrect!!\n\n"))
}
#' Describe Data
#'
#' Produce summaries of various types of variables. Calculate descriptive
#' statistics for x and use Word as reporting tool for the numeric results and
#' for descriptive plots. The appropriate statistics are chosen depending on
#' the class of x. The general intention is to simplify the description
#' process for lazy typers and return a quick, but rich summary.
#'
#' A **2-dimensional table** will be described with it's relative frequencies, a
#' short summary containing the total cases, the dimensions of the table,
#' chi-square tests and some association measures as phi-coefficient,
#' contingency coefficient and Cramer's V. \cr
#' Tables with higher dimensions will simply be printed as flat table,
#' with marginal sums for the first and for the last dimension.
#'
#' `Desc` is a **generic function**. It dispatches to one of the methods above
#' depending on the class of its first argument. Typing `?Desc` + TAB at the
#' prompt should present a choice of links: the help pages for each of these
#' `Desc` methods (at least if you're using RStudio, which anyway is
#' recommended). You don't need to use the full name of the method although you
#' may if you wish; i.e., `Desc(x)` is idiomatic R but you can bypass method
#' dispatch by going direct if you wish: `Desc.numeric(x)`.
#'
#' This function produces a rich description of a **factor**, containing length,
#' number of NAs, number of levels and detailed frequencies of all levels. The
#' order of the frequency table can be chosen between descending/ascending
#' frequency, labels or levels. For ordered factors the order default is
#' `"level"`. Character vectors are treated as unordered factors Desc.char
#' converts x to a factor an processes x as factor.\cr
#' Desc.ordered does nothing more than changing the standard order for the
#' frequencies to it's intrinsic order, which means order `"level"`
#' instead of `"desc"` in the factor case.
#'
#' Description interface for **dates**. We do here what seems reasonable for
#' describing dates. We start with a short summary about length, number of NAs
#' and extreme values, before we describe the frequencies of the weekdays and
#' months, rounded up by a chi-square test.
#'
#' A **2-dimensional table** will be described with it's relative frequencies, a
#' short summary containing the total cases, the dimensions of the table,
#' chi-square tests and some association measures as phi-coefficient,
#' contingency coefficient and Cramer's V. \cr
#' Tables with higher dimensions will simply be printed as flat table,
#' with marginal sums for the first and for the last dimension.
#'
#' Note that `NA`s cannot be handled by this interface, as tables in general come
#' in "as.is", say basically as a matrix without any further information about
#' potentially previously cleared NAs.
#'
#' Description of a **dichotomous variable**. This can either be a logical vector,
#' a factor with two levels or a numeric variable with only two unique values.
#' The confidence levels for the relative frequencies are calculated by
#' [BinomCI()], method `"Wilson"` on a confidence level defined
#' by `conf.level`. Dichotomous variables can easily be condensed in one
#' graphical representation. Desc for a set of flags (=dichotomous variables)
#' calculates the frequencies, a binomial confidence interval and produces a
#' kind of dotplot with error bars. Motivation for this function is, that
#' dichotomous variable in general do not contain intense information.
#' Therefore it makes sense to condense the description of sets of dichotomous
#' variables.
#'
#' The **formula interface** accepts the formula operators `+`, `:`,
#' `*`, `I()`, `1` and evaluates any function. The left hand
#' side and right hand side of the formula are evaluated the same way. The
#' variable pairs are processed in dependency of their classes.
#'
#' `Word` This function is not thought of being directly run by the end user.
#' It will normally be called automatically, when a pointer to a Word instance
#' is passed to the function [Desc()].\cr
#' However `DescWrd` takes
#' some more specific arguments concerning the Word output (like `font` or
#' `fontsize`), which can make it necessary to call the function directly.
#'
#' @aliases
#' Desc
#' Desc.default
#' Desc.data.frame
#' Desc.list
#' Desc.formula
#' Desc.numeric
#' Desc.integer
#' Desc.factor
#' Desc.ordered
#' Desc.character
#' Desc.logical
#' Desc.Date
#' Desc.table
#' print.Desc
#' plot.Desc
#'
#' @param x the object to be described. This can be a data.frame, a list, a
#' table or a vector of the classes: numeric, integer, factor, ordered factor,
#' logical.
#'
#' @param main (character|`NULL`|`NA`), the main title(s).
#' - If `NULL`, the title will be composed as:
#' - variable name (class(es)),
#' - resp. number - variable name (class(es)) if the `enum` option
#' is set to `TRUE.`
#' - Use `NA` if no caption should be printed at all.
#'
#' @param wrd the pointer to a running MS Word instance, as created by
#' [GetNewWrd()] (for a new one) or by [GetCurrWrd()] for an existing
#' one. All output will then be redirected there. Default is `NULL`,
#' which will report all results to the console.
#'
#' @param digits integer. With how many digits should the relative frequencies
#' be formatted? Default can be set by
#' [DescToolsOptions(digits=x)][DescToolsOptions()].
#'
#' @param maxrows numeric; defines the maximum number of rows in a frequency
#' table to be reported. For factors with many levels it is often not
#' interesting to see all of them. Default is set to 12 most frequent ones
#' (resp. the first ones if `ord` is set to `"levels"` or
#' `"names"`).
#'
#' For a numeric argument x `maxrows` is the minimum
#' number of unique values needed for a numeric variable to be treated as
#' continuous. If left to its default `NULL`, x will be regarded as
#' continuous if it has more than 12 single values. In this case the list of
#' extreme values will be displayed and the frequency table else.
#'
#' If `maxrows` is < 1 it will be interpreted as percentage. In this case
#' just as many rows, as the `maxrows` most frequent levels will be
#' shown. Say, if `maxrows` is set to `0.8`, then the number of rows is
#' fixed so, that the highest cumulative relative frequency is the first one
#' going beyond 0.8.
#'
#' Setting `maxrows` to `Inf` will unconditionally report all values
#' and also produce a plot with type "h" instead of a histogram.
#'
#' @param ord character out of `"name"` (alphabetical order),
#' `"level"`, `"asc"` (by frequencies ascending), `"desc"` (by
#' frequencies descending) defining the order for a frequency table as used for
#' factors, numerics with few unique values and logicals. Factors (and
#' character vectors) are by default ordered by their descending frequencies,
#' ordered factors by their natural order.
#'
#' @param rfrq a string with 3 characters, each of them being `1` or
#' `0`, defining which percentages should be reported. The first position
#' is interpreted as total percentages, the second as row percentages and the
#' third as column percentages. "`011`" hence produces a table output with
#' row and column percentages. If set to `NULL` `rfrq` is defined in
#' dependency of `verbose` (`verbose = 1` sets `rfrq` to
#' `"000"` and else to `"111"`, latter meaning all percentages will
#' be reported.) \cr
#' Applies only to tables and is ignored else.
#'
#' @param margins a vector, consisting out of 1 and/or 2. Defines the margin
#' sums to be included. Row margins are reported if margins is set to 1. Set it
#' to 2 for column margins and c(1,2) for both. \cr
#' Default is `NULL` (none).\cr
#' Applies only to tables and is ignored else.
#'
#' @param verbose integer out of `c(2, 1, 3)` defining the verbosity of
#' the reported results. 2 (default) means medium, 1 less and 3 extensive
#' results. \cr
#' Applies only to tables and is ignored else.
#'
#' @param conf.level confidence level of the interval. If set to `NA` no
#' confidence interval will be calculated. Default is 0.95.
#'
#' @param dprobs,mprobs a vector with the probabilities for the Chi-Square test
#' for days, resp. months, when describing a `Date` variable. If this is
#' left to `NULL` (default) then a uniform distribution will be used for
#' days and a monthdays distribution in a non leap year (p = c(31/365, 28/365,
#' 31/365, ...)) for the months. \cr
#' Applies only to `Dates` and is ignored else.
#'
#' @param enum logical, determining if in data.frames and lists a sequential
#' number should be included in the main title. Default is TRUE. The reason for
#' this option is, that if a Word report with enumerated headings is created,
#' the numbers may be redundant or inconsistent.
#'
#' @param plotit logical. Should a plot be created? The plot type will be
#' chosen according to the classes of variables (roughly following a
#' numeric-numeric, numeric-categorical, categorical-categorical logic).
#' Default can be defined by option `plotit`, if it does not exist then
#' it's set to `FALSE`.
#'
#' @param sep character. The separator for the title. By default a line of
#' `"-"` for the current width of the screen `(options("width"))`
#' will be used.
#'
#' @param nolabel logical, defining if labels (defined as attribute with the
#' name `label`, as done by `Label`) should be plotted.
#'
#' @param formula a formula of the form `lhs ~ rhs` where `lhs` gives
#' the data values and rhs the corresponding groups.
#'
#' @param data an optional matrix or data frame containing the variables in the
#' formula `formula`. By default the variables are taken from
#' `environment(formula)`.
#'
#' @param subset an optional vector specifying a subset of observations to be
#' used.
#'
#' @param nomain logical, determines if the main title of the output is printed
#' or not, default is `TRUE`.
#'
#' @param \dots further arguments to be passed to or from other methods.
#' For the internal default method these can include:
#' \describe{
#'
#' \item{`p`}{a vector of probabilities of the same length of `x`.
#' An error is given if any entry of `p` is negative.
#' This argument will be passed on to [chisq.test()][stats::chisq.test()].
#' Default is `rep(1/length(x), length(x))`.}
#'
#' \item{`add_ni`}{logical. Indicates if the group length should be
#' displayed in the boxplot.}
#'
#' \item{`smooth`}{character, either "loess" or "smooth.spline" defining
#' the type of smoother to be used in num ~ num plots. Default is "loess" for
#' n < 500 and "smooth.spline" otherwise.}
#' }
#'
#' @return A list containing the following components:
#'
#' \item{length}{the length of the vector (n + NAs).}
#' \item{n}{the valid entries (NAs are excluded)}
#' \item{NAs}{number of NAs}
#' \item{unique}{number of unique values. }
#' \item{0s}{number of zeros}
#' \item{mean}{arithmetic mean}
#' \item{MeanSE}{standard error of the mean, as calculated by [MeanSE()].}
#' \item{quant}{a table of quantiles, as calculated by
#' [quantile(x, probs = c(.05,.10,.25,.5,.75,.9,.95), na.rm = TRUE)][stats::quantile()].
#' }
#' \item{sd}{standard deviation}
#' \item{vcoef}{coefficient of variation: `mean(x)` / `sd(x)`.}
#' \item{mad}{median absolute deviation ([stats::mad()]).}
#' \item{IQR}{interquartile range }
#' \item{skew}{skewness, as calculated by [Skew()].}
#' \item{kurt}{kurtosis, as calculated by [Kurt()].}
#' \item{highlow}{the lowest and the highest values, reported with their
#' frequencies in brackets, if > 1.}
#' \item{frq}{a data.frame of absolute and relative frequencies given by
#' [Freq()] if `maxlevels` > unique values in the vector.}
#'
#' @author Andri Signorell <andri@@signorell.net>
#'
#' @seealso
#' [base::summary()], [base::plot()]
#'
#' @concept Desc
#' @family Statistical summary functions
#' @keywords print univar multivariate
#'
#'
#' @export
#'
#' @examples
#'
#' opt <- DescToolsOptions()
#'
#' # implemented classes:
#' Desc(d.pizza$wrongpizza) # logical
#' Desc(d.pizza$driver) # factor
#' Desc(d.pizza$quality) # ordered factor
#' Desc(as.character(d.pizza$driver)) # character
#' Desc(d.pizza$week) # integer
#' Desc(d.pizza$delivery_min) # numeric
#' Desc(d.pizza$date) # Date
#'
#' Desc(d.pizza)
#'
#' Desc(d.pizza$wrongpizza, main="The wrong pizza delivered", digits=5)
#'
#' Desc(table(d.pizza$area)) # 1-dim table
#' Desc(table(d.pizza$area, d.pizza$operator)) # 2-dim table
#' Desc(table(d.pizza$area, d.pizza$operator, d.pizza$driver)) # n-dim table
#'
#' # expressions
#' Desc(log(d.pizza$temperature))
#' Desc(d.pizza$temperature > 45)
#'
#' # supported labels
#' Label(d.pizza$temperature) <- "This is the temperature in degrees Celsius
#' measured at the time when the pizza is delivered to the client."
#' Desc(d.pizza$temperature)
#' # try as well: Desc(d.pizza$temperature, wrd=GetNewWrd())
#'
#' z <- Desc(d.pizza$temperature)
#' print(z, digits=1, plotit=FALSE)
#' # plot (additional arguments are passed on to the underlying plot function)
#' plot(z, main="The pizza's temperature in Celsius", args.hist=list(breaks=50))
#'
#'
#' # formula interface for single variables
#' Desc(~ uptake + Type, data = CO2, plotit = FALSE)
#'
#' # bivariate
#' Desc(price ~ operator, data=d.pizza) # numeric ~ factor
#' Desc(driver ~ operator, data=d.pizza) # factor ~ factor
#' Desc(driver ~ area + operator, data=d.pizza) # factor ~ several factors
#' Desc(driver + area ~ operator, data=d.pizza) # several factors ~ factor
#' Desc(driver ~ week, data=d.pizza) # factor ~ integer
#'
#' Desc(driver ~ operator, data=d.pizza, rfrq="111") # alle rel. frequencies
#' Desc(driver ~ operator, data=d.pizza, rfrq="000",
#' verbose=3) # no rel. frequencies
#'
#' Desc(price ~ delivery_min, data=d.pizza) # numeric ~ numeric
#' Desc(price + delivery_min ~ operator + driver + wrongpizza,
#' data=d.pizza, digits=c(2,2,2,2,0,3,0,0) )
#'
#' Desc(week ~ driver, data=d.pizza, digits=c(2,2,2,2,0,3,0,0)) # define digits
#'
#' Desc(delivery_min + weekday ~ driver, data=d.pizza)
#'
#'
#' # without defining data-parameter
#' Desc(d.pizza$delivery_min ~ d.pizza$driver)
#'
#'
#' # with functions and interactions
#' Desc(sqrt(price) ~ operator : factor(wrongpizza), data=d.pizza)
#' Desc(log(price+1) ~ cut(delivery_min, breaks=seq(10,90,10)),
#' data=d.pizza, digits=c(2,2,2,2,0,3,0,0))
#'
#' # response versus all the rest
#' Desc(driver ~ ., data=d.pizza[, c("temperature","wine_delivered","area","driver")])
#'
#' # all the rest versus response
#' Desc(. ~ driver, data=d.pizza[, c("temperature","wine_delivered","area","driver")])
#'
#' # pairwise Descriptions
#' p <- CombPairs(c("area","count","operator","driver","temperature","wrongpizza","quality"), )
#' for(i in 1:nrow(p))
#' print(Desc(formula(gettextf("%s ~ %s", p$X1[i], p$X2[i])), data=d.pizza))
#'
#'
#' # get more flexibility, create the table first
#' tab <- as.table(apply(HairEyeColor, c(1,2), sum))
#' tab <- tab[,c("Brown","Hazel","Green","Blue")]
#'
#' # display only absolute values, row and columnwise percentages
#' Desc(tab, row.vars=c(3, 1), rfrq="011", plotit=FALSE)
#'
#' # do the plot by hand, while setting the colours for the mosaics
#' cols1 <- SetAlpha(c("sienna4", "burlywood", "chartreuse3", "slategray1"), 0.6)
#' cols2 <- SetAlpha(c("moccasin", "salmon1", "wheat3", "gray32"), 0.8)
#' plot(Desc(tab), col1=cols1, col2=cols2)
#'
#'
#' # use global format options for presentation
#' Fmt(abs=as.fmt(digits=0, big.mark=""))
#' Fmt(per=as.fmt(digits=2, fmt="%"))
#' Desc(area ~ driver, d.pizza, plotit=FALSE)
#'
#' Fmt(abs=as.fmt(digits=0, big.mark="'"))
#' Fmt(per=as.fmt(digits=3, ldigits=0))
#' Desc(area ~ driver, d.pizza, plotit=FALSE)
#'
#' # plot arguments can be fixed in detail
#' z <- Desc(BoxCox(d.pizza$temperature, lambda = 1.5))
#' plot(z, mar=c(0, 2.1, 4.1, 2.1), args.rug=TRUE, args.hist=list(breaks=50),
#' args.dens=list(from=0))
#'
#' # The default description for count variables can be inappropriate,
#' # the density curve does not represent the variable well.
#' set.seed(1972)
#' x <- rpois(n = 500, lambda = 5)
#' Desc(x)
#' # but setting maxrows to Inf gives a better plot
#' Desc(x, maxrows = Inf)
#'
#'
#' # Output into word document (Windows-specific example) -----------------------
#' # by simply setting wrd=GetNewWrd()
#' \dontrun{
#'
#' # create a new word instance and insert title and contents
#' wrd <- GetNewWrd(header=TRUE)
#'
#' # let's have a subset
#' d.sub <- d.pizza[,c("driver", "date", "operator", "price", "wrongpizza")]
#'
#' # do just the univariate analysis
#' Desc(d.sub, wrd=wrd)
#' }
#'
#' DescToolsOptions(opt)
#'
#'
Desc <- function(x, ..., main = NULL, plotit = NULL, wrd = NULL) {
if (is.null(wrd)) {
UseMethod("Desc")
} else {
if (!IsValidHwnd(wrd)) {
warning("wrd is not a valid handle to a running Word instance.")
} else {
if (is.null(main) && !is.recursive((x))) {
main <- deparse(substitute(x))
}
z <- Desc(x, main = main, plotit = FALSE, ..., wrd = NULL)
# only if header exists (it does not for single variables!!)
if (!is.null(z[["_objheader"]])) {
z[["_objheader"]]["main"] <- gettextf(
"Describe %s (%s):", paste(deparse(substitute(x)), collapse = " "),
paste(class(x), collapse = " ,")
)
}
printWrd(x = z, main = main, plotit = plotit, ..., wrd = wrd)
}
}
}
#' @rdname Desc
#' @export
Desc.numeric <- function(x, main = NULL,
maxrows = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
maxrows = maxrows, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.integer <- function(x, main = NULL,
maxrows = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
maxrows = maxrows, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.factor <- function(x, main = NULL,
maxrows = NULL, ord = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
maxrows = maxrows, ord = ord, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.labelled <- function(x, main = NULL,
maxrows = NULL, ord = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
xname <- deparse(substitute(x))
lbl <- Label(x)
x <- factor(x, labels = names(attr(x, "labels")))
Label(x) <- lbl
return(desc(
x = x, xname = xname, main = main, digits = digits,
maxrows = maxrows, ord = ord, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.ordered <- function(x, main = NULL,
maxrows = NULL, ord = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
maxrows = maxrows, ord = ord, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.character <- function(x, main = NULL,
maxrows = NULL, ord = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
maxrows = maxrows, ord = ord, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.ts <- function(x, main = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.logical <- function(x, main = NULL,
ord = NULL, conf.level = 0.95,
plotit = NULL, sep = NULL, digits = NULL, ...) {
if (is.null(ord)) ord <- "level"
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
ord = ord, conf.level = conf.level, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.Date <- function(x, main = NULL,
dprobs = NULL, mprobs = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
dprobs = dprobs, mprobs = mprobs, plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.table <- function(x, main = NULL,
conf.level = 0.95, verbose = 2,
rfrq = "111", margins = c(1, 2),
plotit = NULL, sep = NULL, digits = NULL, ...) {
return(desc(
x = x,
xname = deparse(substitute(x)), main = main, digits = digits,
conf.level = conf.level, verbose = verbose, rfrq = rfrq, margins = margins,
plotit = plotit, sep = sep, ...
))
}
#' @rdname Desc
#' @export
Desc.default <- function(x, main = NULL, maxrows = NULL, ord = NULL,
conf.level = 0.95, verbose = 2, rfrq = "111", margins = c(1, 2),
dprobs = NULL, mprobs = NULL,
plotit = NULL, sep = NULL, digits = NULL, ...) {
desc(x,
xname = deparse(substitute(x)), main = NULL, digits = NULL,
maxrows = NULL, ord = NULL,
conf.level = 0.95, verbose = 2, rfrq = "111", margins = c(1, 2),
dprobs = NULL, mprobs = NULL,
plotit = NULL, sep = NULL, ...
)
}
desc <- function(x, main = NULL, xname = deparse(substitute(x)), digits = NULL,
maxrows = NULL, ord = NULL,
conf.level = 0.95, verbose = 2, rfrq = "111", margins = c(1, 2),
dprobs = NULL, mprobs = NULL,
plotit = NULL, sep = NULL, ...) {
# univariate Desc
# z <- list(xname = deparse(substitute(x)),
# label = attr(x, "label"))
# we have to collapse xname here, else there are some breaks like in
# Desc(Recode(d.pizza$driver, carp=c("Carpenter","Carter"),
# arm=c("Butcher","Farmer"), elselevel = "Anyone"))
z <- list(
xname = paste(StrTrim(xname), collapse = ""),
label = attr(x, "label")
)
if (any(class(x) %in% c("table", "matrix"))) {
ntot <- length(x)
n <- sum(x, na.rm = TRUE) # without NAs
NAs <- NA # number of NAs in a table, how to?? after all they're pairs..
} else if (identical(class(x), "NULL")) {
ntot <- 0
x <- NULL
n <- 0
NAs <- 0
} else if (inherits(x, "ts")) {
ntot <- length(x) # total count
# x <- x[!is.na(x)] do not omit NAs for timeseries
n <- length(x) # now without NAs
NAs <- ntot - n # number of NAs
} else {
ntot <- length(x) # total count
x <- x[!is.na(x)]
n <- length(x) # now without NAs
NAs <- ntot - n # number of NAs
}
# ignore class AsIs from I(...) and keep only the rest of class(es)
if (!is.null(x)) {
class(x) <- class(x)[class(x) != "AsIs"]
}
z <- c(z,
main = main,
class = class(x)[1], # highest class here
classlabel = paste(class(x), collapse = ", "),
length = ntot,
n = n,
NAs = NAs,
plotit = plotit,
digits = digits,
sep = sep
)
# define order for displaying frequencies of factors,
# default level order for ordered factors
# Descending frequencies for unordered factors
if (is.null(ord)) {
if (inherits(x, "ordered") ||
inherits(x, "numeric") ||
inherits(x, "integer")) {
ord <- "level"
} else if (inherits(x, "factor")) {
ord <- if (nlevels(x) == 2) "level" else "desc"
}
}
ord <- match.arg(arg = ord, choices = c("desc", "asc", "name", "level"))
# define default main title
if (is.null(main)) {
z$main <- gettextf("%s (%s)", z$xname, paste(class(x), collapse = ", "))
}
# if not an empty vector (or only NAs)
if (n > 0) {
# send na stripped x to calcDesc, with n being vector length
z <- c(z, calcDesc(
x = x, n = n, digits = digits, conf.level = conf.level,
ord = ord, maxrows = maxrows,
verbose = verbose, rfrq = rfrq, margins = margins, ...
))
if (z$class %nin% c("numeric", "Date") &&
!is.null(z$unique) &&
!is.na(z$unique) &&
z$unique <= 2 &&
!(z$class %in% c("factor", "ordered") && z$levels > 2)) {
# escalate to logical description if only two values
if (is.null(main)) {
z$main <- gettextf(
"%s (%s - dichotomous)", z$xname, paste(class(x), collapse = ", ")
)
}
if (z$class %in% c("integer")) {
z$afrq <- cbind(z$small$freq)
rownames(z$afrq) <- z$small$val
}
if (z$class %in% c("factor", "ordered", "character")) {
z$afrq <- cbind(z$freq$freq)
rownames(z$afrq) <- z$freq$level
}
z$rfrq <- BinomCI(z$afrq, n, conf.level = conf.level)
z$conf.level <- conf.level
z$class <- "logical"
}
} else {
z$unique <- NA
z$noplot <- TRUE
z$plotit <- FALSE
}
# why did I do that? not ok for frequencies??
# anyway I may not overwrite digits here
# if(is.null(digits) && !is.null(z$freq)) z$digits <- 1
# make a list
z <- list(z)
class(z) <- "Desc"
return(z)
}
#' @rdname Desc
#' @export
Desc.data.frame <- function(x, main = NULL, plotit = NULL, enum = TRUE,
sep = NULL, ...) {
res <- Desc.list(
x = x, main = main, plotit = plotit, enum = enum, sep = sep, ...
)
res[["_objheader"]][["main"]] <- gettextf(
"Describe %s (%s):",
gsub(" +", " ", paste(deparse(substitute(x)), collapse = " ")),
paste(class(x), collapse = ", ")
)
res[["_objheader"]][["abstract"]] <- Abstract(x)
attr(res[["_objheader"]][["abstract"]], "main") <-
res[["_objheader"]][["main"]]
res[["_objheader"]][["str"]] <- .CaptOut(
res[["_objheader"]][["abstract"]],
width = getOption("width")
)[-c(1:3)]
return(res)
}
#' @rdname Desc
#' @export
Desc.list <- function(x, main = NULL, plotit = NULL, enum = TRUE,
sep = NULL, ...) {
xname <- deparse(substitute(x))
# header for the data.frame of the list
if (is.null(names(x))) {
names(x) <- seq_along(x)
}
# default main titles if main is left to NULL
def.main <- is.null(main)
if (def.main) {
main <- paste(
if (enum) {
paste(seq_along(names(x)), "- ")
}, names(x),
sep = ""
)
} else {
main <- rep(main, length.out = ncol(x))
}
lst <- list()
for (i in seq_along(x)) {
xn <- names(x)[i]
lst[[xn]] <- Desc(x[[xn]], plotit = plotit, sep = sep, ...)[[1]]
lst[[xn]]["xname"] <- xn
if (def.main) {
lst[[xn]]["main"] <-
gsub("x[[xn]]", main[i], lst[[xn]]["main"], fixed = TRUE)
} else {
lst[[xn]]["main"] <- main[i]
}
}
header <- list(
str = .CaptOut(
Str(x, list.len = Inf)
),
xname = xname,
label = Label(x),
class = "header",
sep = sep,
# main = gettextf("Describe %s (%s):", deparse(substitute(x)), class(x))
# we might be too late for substituting here... ?
main = gettextf("Describe %s (%s):", xname, class(x))
)
# class(header) <- "Desc"
lst <- append(lst, list(header), after = 0)
names(lst)[1] <- "_objheader"
class(lst) <- "Desc"
return(lst)
}
#' @rdname Desc
#' @export
Desc.formula <- function(formula, data = parent.frame(),
subset, main = NULL, plotit = NULL, digits = NULL, ...) {
mf <- match.call(expand.dots = FALSE)
subset.expr <- mf$subset
mf$subset <- NULL
if (!missing(subset)) {
s <- eval(subset.expr, data, parent.frame())
data <- data[s, ]
}
mm <- DescTools::ParseFormula(formula = formula, data = data)
lst <- list()
if (length(mm$formula) == 2L) {
for (x in mm$rhs$vars) { # for all x variables
lst[x] <- Desc(mm$rhs$mf.eval[, x], plotit = plotit, digits = digits, ...)
if (deparse(substitute(data)) != "parent.frame()") {
lst[[x]]$main <-
gettextf("%s$%s (%s)", deparse(substitute(data)), x, lst[[x]]$class)
} else {
lst[[x]]$main <- gettextf("%s (%s)", x, lst[[x]]$class)
}
}
} else if (length(mm$rhs$vars) == 0 & length(mm$lhs$vars) != 0) {
for (x in mm$lhs$vars) { # for all x variables
lst[x] <- Desc(mm$lhs$mf.eval[, x], plotit = plotit, digits = digits, ...)
if (deparse(substitute(data)) != "parent.frame()") {
lst[[x]]$main <-
gettextf("%s$%s (%s)", deparse(substitute(data)), x, lst[[x]]$class)
} else {
lst[[x]]$main <- gettextf("%s (%s)", x, lst[[x]]$class)
}
}
} else {
# don't want AsIs (will come in case of I(...)) to proceed, so just
# coerce to vector an back again
# but don't use the following, as interaction names will be
# set to y.x instead of y:x
# mm$lhs$mf.eval <- data.frame(lapply(mm$lhs$mf.eval, as.vector))
# mm$rhs$mf.eval <- data.frame(lapply(mm$rhs$mf.eval, as.vector))
for (i in which(lapply(mm$lhs$mf.eval, class) == "AsIs")) {
mm$lhs$mf.eval[, i] <- as.vector(mm$lhs$mf.eval[, i])
}
for (i in which(lapply(mm$rhs$mf.eval, class) == "AsIs")) {
mm$rhs$mf.eval[, i] <- as.vector(mm$rhs$mf.eval[, i])
}
for (resp in mm$lhs$vars) { # for all response variables
for (pred in mm$rhs$vars) { # evalutate for all conditions
y <- mm$lhs$mf.eval[, resp]
x <- mm$rhs$mf.eval[, pred]
if (IsDichotomous(y, na.rm = TRUE)) y <- factor(y)
if (IsDichotomous(x, na.rm = TRUE)) x <- factor(x)
names(y) <- resp
names(x) <- pred
lst[[paste(resp, pred, sep = " ~ ")]] <-
calcDesc.bivar(x = y, g = x, xname = resp, gname = pred, ...)
lst[[paste(resp, pred, sep = " ~ ")]]["plotit"] <- plotit
# would not accept vectors when ["digits"] used. Why??:
lst[[paste(resp, pred, sep = " ~ ")]][["digits"]] <- digits
lst[[paste(resp, pred, sep = " ~ ")]]["main"] <- if (is.null(main)) {
gettextf(
"%s ~ %s%s",
lst[[paste(resp, pred, sep = " ~ ")]]["xname"],
lst[[paste(resp, pred, sep = " ~ ")]]["gname"],
# don't display parent.frame() for simple formulas in main titles
if ((ctxt <- deparse(substitute(data))) == "parent.frame()") {
""
} else {
paste0(" (", ctxt, ")")
}
)
}
}
}
if (!is.null(main)) {
main <- rep(main, length.out = length(lst))
for (i in seq_along(lst)) {
lst[[i]]["main"] <- main[i]
}
}
}
attr(lst, "call") <- deparse(sys.call())
class(lst) <- "Desc"
return(lst)
}
calcDesc <- function(x, ...) {
UseMethod("calcDesc")
}
calcDesc.default <- function(x, ...) {
if (!is.null(class(x))) {
# cat(gettextf("\nSorry, don't know how to Desc class(es) %s (%s)!\n\n",
# paste(class(x), collapse = ", "), deparse(substitute(x))))
r <- "unhandled class"
} else {
# cat(gettextf("\nObject %s does not exist!\n\n", deparse(substitute(x))))
r <- "no object"
}
invisible(r)
}
calcDesc.numeric <- function(x, n, maxrows = NULL, conf.level = 0.95,
include_x = TRUE, ...) {
probs <- c(0, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 1)
# the quantiles, totally analogue to the core of stats::quantile:
index <- 1 + (n - 1) * probs
lo <- floor(index)
hi <- ceiling(index)
x <- sort(x, partial = unique(c(lo, hi)))
# WHOLE x MUST be sorted in order to get the smallest and largest values,
# as well as the number of unique values!!!
# old: x <- sort(x)
# x <- sort.int(x, method="quick") # somewhat faster than "shell"
qs <- x[lo]
i <- which(index > lo)
h <- (index - lo)[i]
qs[i] <- (1 - h) * qs[i] + h * x[hi[i]]
names(qs) <-
c("min", ".05", ".10", ".25", "median", ".75", ".90", ".95", "max")
# ... here we go, all we need so far is in qs
# proceed with the parameteric stuff, we cannot calc mean faster than R,
# so do it here
# meanx <- mean.default(x) # somewhat faster than mean
# we send the SORTED vector WITHOUT NAs to the C++ function to calc
# the power sum(s)
psum <- .Call("_DescTools_n_pow_sum", PACKAGE = "DescTools", x)
# this is method 3 in the usual functions Skew and Kurt
skewx <- ((1 / n * psum$sum3) / (psum$sum2 / n)^1.5) * ((n - 1) / n)^(3 / 2)
kurtx <-
((((1 / n * psum$sum4) / (psum$sum2 / n)^2) - 3) + 3) * (1 - 1 / n)^2 - 3
# get std dev here
sdx <- sqrt(psum$sum2 / (n - 1))
# get the mode
modex <- Mode(x)
# check for remarkably frequent values in a numeric variable
# say the most frequent value has significantly more than 5% from the total sample
modefreq_crit <-
binom.test(ZeroIfNA(attr(modex, "freq")), n = n, p = 0.05, alternative = "greater")
if (modefreq_crit$p.value < 0.05 & psum$unique > 12) {
modefreq_crit <- gettextf(
"heap(?): remarkable frequency (%s) for the mode(s) (= %s)",
Format(modefreq_crit$estimate, fmt = "%", digits = 1),
paste(modex, collapse = ", ")
)
} else {
modefreq_crit <- NA
}
# we display frequencies, when unique values <=12 else we set maxrows = 0
# which will display extreme values as high-low list
if (is.null(maxrows)) {
maxrows <- ifelse(psum$unique <= 12, 12, 0)
}
if (maxrows > 0) {
freq <- Freq(factor(x))
colnames(freq)[1] <- "value"
# use maxrows as percentage, when < 1
if (maxrows < 1) {
maxrows <- sum(freq[, 5] < maxrows) + 1
}
} else {