-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiscresults.R
3473 lines (3272 loc) · 121 KB
/
miscresults.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
# miscresults.R
#
# -----------------------------------------------------------------------------
# Reporting standards
# -----------------------------------------------------------------------------
# Some guidelines on reporting statistics include:
# - https://support.jmir.org/hc/en-us/articles/360019690851-Guidelines-for-Reporting-Statistics
# - https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2959222/
# ... argues for "mean (SD)" not "mean ± SD" because some will assume that
# ± is for confidence intervals.
# - https://en.wikipedia.org/wiki/Plus%E2%80%93minus_sign
# ... ± typically SD or SE.
# - https://en.wikipedia.org/wiki/Margin_of_error
# - Confidence intervals in JMIR style use an en dash "a–b", or "a to b" if
# any are negative. And confidence intervals frequently do involve a negative
# number. An alternative is [a, b], using inclusive (square) brackets.
# - Ranges typically use en dashes in writing, and less frequently involve
# negative numbers.
# - But generally it's good to be explicit! So we'll be explicit for the
# defaults.
#
# -----------------------------------------------------------------------------
# "Standard" markdown notation
# -----------------------------------------------------------------------------
# - https://en.wikipedia.org/wiki/Markdown discusses evolution and versions
# - https://datatracker.ietf.org/doc/html/rfc7763 is an early standard
# - https://datatracker.ietf.org/doc/html/rfc7764 covers some versions; Pandoc
# is the only one with a superscript/subscript extension then.
# So there's no common standard for these features.
#
# -----------------------------------------------------------------------------
# Markdown for flextable
# -----------------------------------------------------------------------------
# ftExtra uses Pandoc markdown;
# - https://www.uv.es/wikibase/doc/cas/pandoc_manual_2.7.3.wiki?53
# - https://ftextra.atusy.net/articles/format_columns
#
# Notably:
#
# - italics: *x*
# - bold: **x**
# - subscript: ~x~
# - superscript: ^x^
# - newline: backslash then newline immediately (see
# miscresults$MARKDOWN_NEWLINE below)
#
# Less often:
#
# - code: `x`
# - underline: [x]{.underline}
#
# -----------------------------------------------------------------------------
# Markdown for ggplot/ggtext
# -----------------------------------------------------------------------------
# Markdown syntax for ggplot, which is via ggtext::element_markdown(), is given
# by:
#
# library(ggtext)
# vignette("theme_elements")
# vignette("plotting_text")
#
# ... in brief:
# *italic*
# **bold**
# <sup>superscript</sup> AND SOMETIMES BUT NOT CONSISTENTLY ^superscript^
# <sub>subscript</sub> AND SOMETIMES BUT NOT CONSISTENTLY ~subscript~
# <br>
#
# etc. In contrast, ftExtra supports ^superscript^ and ~subscript~, but not
# <sup>superscript</sup> or <sub>subscript</sub>.
#
# Since there is inconsistency with the ^~ notation, and with these:
# working via Docker not working via CPFT
# ggtext_0.1.2 ggtext_0.1.2
# ggplot2_3.4.4 ggplot2_3.5.1
# ... I'm not sure what the issue is here, so we'll use separate markdown for
# tables and figures where this applies. See the function
# miscresults$markdown_ggtext_to_flextable()
local({
tmp_require_package_namespace <- function(...) {
packages <- as.character(match.call(expand.dots = FALSE)[[2]])
for (p in packages) if (!requireNamespace(p)) install.packages(p)
}
tmp_require_package_namespace(
car, # for car::Anova
flextable,
ftExtra, # for markup within flextable tables
rcompanion, # for wilcoxonZ
rlang, # for dots_n
tidyverse
)
})
# =============================================================================
# Namespace-like method: http://stackoverflow.com/questions/1266279/#1319786
# =============================================================================
miscresults <- new.env()
# =============================================================================
# Constants
# =============================================================================
# -----------------------------------------------------------------------------
# Unicode
# -----------------------------------------------------------------------------
# NOTE RE UNICODE: This can be challenging under Windows. The problem isn't
# usually in handling Unicode, it's in representing it in the file encoding,
# since Windows does not use UTF-8 file encoding by default. It's therefore
# preferable to use "\u<hexcode">, e.g. "\u2013" for an en dash. This is an
# ASCII file representation of a Unicode character, which works fine.
# Basic ASCII
miscresults$MARKDOWN_NEWLINE <- "\\\n" # two characters: backslash, newline
# ... Line break: https://ftextra.atusy.net/articles/format_columns
# Common punctuation
miscresults$HYPHEN <- "-" # plain ASCII
# Marks in the traditional order for footnotes:
# - https://en.wikipedia.org/wiki/Note_(typography)
miscresults$ASTERISK <- "*"
miscresults$DAGGER <- "\u2020"
miscresults$DOUBLE_DAGGER <- "\u2021"
miscresults$SECTION <- "\u00A7"
miscresults$DOUBLE_VERTICAL_LINE <- "\u2016"
miscresults$PILCROW <- "\u00B6"
# Dashes and mathematical symbols
miscresults$EN_DASH <- "\u2013"
miscresults$MINUS <- "\u2212"
miscresults$MULTIPLY <- "\u00D7"
miscresults$MULTIPLICATION_DOT <- "\u22C5"
miscresults$PLUS_MINUS <- "\u00B1" # case-insensitive
# Greek letters
miscresults$ALPHA <- "\u03B1"
miscresults$CHI_LOWER <- "\u03C7"
# Accented Latin characters
miscresults$LOWER_CASE_A_ACUTE <- "\u00E1"
miscresults$UPPER_CASE_S_CARON <- "\u0160"
# Arrows and arrow-like symbols
# https://www.compart.com/en/unicode/block/U+2190
miscresults$UP_ARROW <- "\u2191"
miscresults$DOWN_ARROW <- "\u2193"
miscresults$LEFT_RIGHT_ARROW <- "\u2194"
miscresults$UP_ARROW_FROM_BAR <- "\u21A5"
miscresults$DOWN_ARROW_FROM_BAR <- "\u21A7"
# https://www.compart.com/en/unicode/block/U+25A0
miscresults$BLACK_UP_TRIANGLE <- "\u25B2"
miscresults$BLACK_DOWN_TRIANGLE <- "\u25BC"
miscresults$WHITE_UP_TRIANGLE <- "\u25B3"
miscresults$WHITE_DOWN_TRIANGLE <- "\u25BD"
# Other symbols
# https://www.compart.com/en/unicode/block/U+0080
miscresults$MIDDLE_DOT <- "\u00B7"
# Names with accents
miscresults$SIDAK_TXT <- paste0(
miscresults$UPPER_CASE_S_CARON, "id", miscresults$LOWER_CASE_A_ACUTE, "k"
)
# -----------------------------------------------------------------------------
# Other
# -----------------------------------------------------------------------------
miscresults$DEFAULT_DP_FOR_DF <- 1 # decimal places for non-integer degrees of freedom
miscresults$MINIMUM_P_SHOWN <- 2.2e-16
# .Machine$double.eps is 2.220446e-16; however, readers are used to seeing
# "2.2e-16" or equivalent representations in output from R, not "2.22e-16".
miscresults$MINIMUM_F_SHOWN <- 1
miscresults$MINIMUM_ABS_T_SHOWN <- 1
# ... critical value for a two-tailed test at α = 0.05 is ±qt(0.975, df),
# decreasing for higher df, and approaching qnorm(0.975) as df → ∞.
# So that's about 1.96. We might want to report things that didn't
# make it, but 1 seems like a reasonable "definitely do not care"
# threshold.
miscresults$DEFAULT_OMIT_DF_BELOW_MIN_STATS <- TRUE
miscresults$NOT_SIGNIFICANT <- "NS"
miscresults$DEFAULT_ALPHA <- 0.05 # Per Fisher.
miscresults$DEFAULT_CI <- 1 - miscresults$DEFAULT_ALPHA
miscresults$DF_FORMAT_OPTIONS <- c(
"subscript", "roundbracket", "squarebracket"
)
miscresults$R_INTERACTION_MARKER <- stringr::fixed(":")
miscresults$R_RESIDUALS_LABEL <- "Residuals"
miscresults$R_INTERCEPT_LABEL <- "(Intercept)"
miscresults$R_FALSE_TEXT <- "FALSE"
miscresults$R_TRUE_TEXT <- "TRUE"
# =============================================================================
# Helper functions
# =============================================================================
miscresults$is.wholenumber <- function(x, tol = .Machine$double.eps^0.5) {
# per example in ?base::integer
abs(x - round(x)) < tol
}
# Can't use miscresults$ prefix here.
contr.sum.keepnames <- function(...) {
# See type_III_sums_of_squares.R
# https://stackoverflow.com/questions/10808853/why-does-changing-contrast-type-change-row-labels-in-r-lm-summary
conS <- contr.sum(...)
colnames(conS) <- rownames(conS)[-length(rownames(conS))]
# ... For example, if the row names are A-D, this will assign the column
# names to be A-C, dropping the last element.
conS
}
miscresults$markdown_ggtext_to_flextable <- function(x) {
# Converts between different flavours of non-standard markdown.
# Superscript:
sup1_html <- stringr::fixed("<sup>")
sup2_html <- stringr::fixed("</sup>")
sup_md <- "^"
# Subscript:
sub1_html <- stringr::fixed("<sub>")
sub2_html <- stringr::fixed("</sub>")
sub_md <- "~"
# Newline/break:
newline_html <- stringr::fixed("<br>")
newline_md <- miscresults$MARKDOWN_NEWLINE
# Translate all:
return(
x
%>% stringr::str_replace_all(sup1_html, sup_md)
%>% stringr::str_replace_all(sup2_html, sup_md)
%>% stringr::str_replace_all(sub1_html, sub_md)
%>% stringr::str_replace_all(sub2_html, sub_md)
%>% stringr::str_replace_all(newline_html, newline_md)
)
}
# =============================================================================
# Markdown helpers
# =============================================================================
# Use "_" suffix to avoid confusion with e.g. flextable::bold().
miscresults$italic_ <- function(x) {
sprintf("*%s*", x)
}
miscresults$bold_ <- function(x) {
sprintf("**%s**", x)
}
miscresults$superscript_ <- function(x) {
sprintf("^%s^", x)
}
miscresults$subscript_ <- function(x) {
sprintf("~%s~", x)
}
miscresults$abs_ <- function(x) {
sprintf("|%s|", x)
}
# =============================================================================
# Formatting results: basic conversion to "pretty" text formats
# =============================================================================
miscresults$mk_sig_label <- function(
p,
symbol = "*",
sidak_correction_n = 1,
prefix = " ",
prefix_ns = ", ",
ns_text = miscresults$NOT_SIGNIFICANT
) {
# From a p value, return a label, e.g. "**" or "NS", to be attached to that
# p value (in null hypothesis significant testing).
# Optionally, apply a Sidak correction.
p <- miscstat$sidak_corrected_p(p, sidak_correction_n)
return(case_when(
p < 0.00001 ~ paste0(prefix, paste(rep(symbol, 5), collapse = "")), # 10^-5
p < 0.0001 ~ paste0(prefix, paste(rep(symbol, 4), collapse = "")), # 10^-4
p < 0.001 ~ paste0(prefix, paste(rep(symbol, 3), collapse = "")), # 10^-3
p < 0.01 ~ paste0(prefix, paste(rep(symbol, 2), collapse = "")), # 10^-2
p < 0.05 ~ paste0(prefix, paste(rep(symbol, 1), collapse = "")), # Fisher!
TRUE ~ paste0(prefix_ns, ns_text)
))
}
miscresults$mk_p_asterisk_caption <- function(
symbol = "*",
ns_text = miscresults$NOT_SIGNIFICANT,
ns_explanation = "not significant",
suffix = "."
) {
# Makes a helpful caption to match miscresults$mk_sig_label().
paste0(
paste(rep(symbol, 5), collapse = ""), " p < 0.00001; ",
paste(rep(symbol, 4), collapse = ""), " p < 0.0001; ",
paste(rep(symbol, 3), collapse = ""), " p < 0.001; ",
paste(rep(symbol, 2), collapse = ""), " p < 0.01; ",
paste(rep(symbol, 1), collapse = ""), " p < 0.05; ",
ns_text, ", ", ns_explanation,
suffix
)
}
miscresults$fmt_int <- function(
x,
big.mark = get_flextable_defaults()$big.mark,
use_plus = FALSE, # prepend "+" for positive numbers?
na_str = get_flextable_defaults()$na_str,
nan_str = get_flextable_defaults()$nan_str
) {
# Replaces flextable::fmt_int().
flag <- ""
if (use_plus) {
flag <- paste0(flag, "+")
}
txt <- formatC(
x,
format = "d",
flag = flag,
big.mark = big.mark
)
# Convert hyphens to proper minus signs, and trim whitespace:
txt <- stringr::str_trim(
stringr::str_replace_all(txt, miscresults$HYPHEN, miscresults$MINUS)
)
# Deal with NaN and NA (in parallel):
return(case_when(
is.nan(x) ~ nan_str,
is.na(x) ~ na_str,
.default = txt
))
}
miscresults$fmt_float <- function(
x,
allow_sci_notation = TRUE,
include_trailing_zero = TRUE,
sf = get_flextable_defaults()$digits,
use_plus = FALSE, # prepend "+" for positive numbers?
big.mark = get_flextable_defaults()$big.mark,
decimal.mark = get_flextable_defaults()$decimal.mark,
na_str = get_flextable_defaults()$na_str,
nan_str = get_flextable_defaults()$nan_str
) {
# Format a floating-point (real) number, according to a number of
# significant figures, allowing scientific notation or not. Return values
# might look like "0.1", "2.2 × 10^−16^" (the latter using ftExtra markup).
# An extension for flextable::fmt_dbl, using its notation.
flag <- ""
if (include_trailing_zero) {
flag <- paste0(flag, "#")
}
if (use_plus) {
flag <- paste0(flag, "+")
}
if (allow_sci_notation) {
txt <- formatC(
signif(x, digits = sf),
digits = sf,
format = "g",
flag = flag,
big.mark = big.mark,
decimal.mark = decimal.mark
)
# May or may not be in scientific notation.
# If scientific notation:
scimatch <- stringr::str_match(txt, "(.+)e([-+]?)(\\d+)")
# ... may be a matrix, indexed [item, matchgroupnum]
# In case using scientific notation: make it pretty!
radix <- scimatch[, 2]
sign <- scimatch[, 3]
exponent <- scimatch[, 4]
sign <- stringr::str_replace(sign, "[+]", "")
# ... remove + from exponent
exponent <- stringr::str_replace(exponent, "^0+" ,"")
# ... remove leading zeros from exponent
# Use ^...^ for superscript with ftExtra.
txt <- ifelse(
!is.na(scimatch[, 1]),
paste0(
radix, " ", miscresults$MULTIPLY, " 10^", sign, exponent, "^"
),
txt
)
} else {
# https://stackoverflow.com/questions/3245862
txt <- formatC(
signif(x, digits = sf),
digits = sf,
format = "fg",
flag = flag,
big.mark = big.mark,
decimal.mark = decimal.mark
)
}
# Convert hyphens to proper minus signs, and trim whitespace:
txt <- stringr::str_trim(
stringr::str_replace_all(txt, miscresults$HYPHEN, miscresults$MINUS)
)
# Deal with NaN and NA (in parallel):
return(case_when(
is.nan(x) ~ nan_str,
is.na(x) ~ na_str,
.default = txt
))
}
miscresults$mk_p_text <- function(
p,
sf = get_flextable_defaults()$digits,
min_p = miscresults$MINIMUM_P_SHOWN
) {
# From a p value, return a string such as "*p* = 0.03" or "*p* < 2.2e-16".
# Uses fmt_float().
return(ifelse(
p < min_p,
paste0(
miscresults$italic_("p"),
" < ",
miscresults$fmt_float(min_p, sf = sf)
),
paste0(
miscresults$italic_("p"),
" = ",
miscresults$fmt_float(p, sf = sf)
)
))
}
miscresults$mk_p_text_with_label <- function(
p,
sf = get_flextable_defaults()$digits,
sidak_correction_n_for_asterisks = 1,
min_p = miscresults$MINIMUM_P_SHOWN,
ns_text = miscresults$NOT_SIGNIFICANT
) {
# From a p value, return an asterisk-labelled string such as "*p* = 0.03 *"
# or "*p* = 0.5, NS". Optionally, apply a Sidak correction to the labelling
# (without altering the p value itself).
return(paste0(
miscresults$mk_p_text(
p,
sf = sf,
min_p = min_p
),
miscresults$mk_sig_label(
p,
sidak_correction_n = sidak_correction_n_for_asterisks,
ns_text = ns_text
)
))
}
miscresults$mk_df_text <- function(
df,
dp = miscresults$DEFAULT_DP_FOR_DF,
big.mark = "",
decimal.mark = get_flextable_defaults()$decimal.mark
) {
# Format degrees of freedom (df) appropriately -- as an exact integer, or
# to 1 dp if it is not integer (since knowing the fact of not being an
# integer is often quite important!).
# - By default, big.mark is "", not get_flextable_defaults()$big.mark;
# commas in degrees of freedom would be very confusing for F tests, in
# which we will separate the two df numbers by commas anyway.
# - So for consistency, we'll use "" as the default.
return(ifelse(
as.integer(df) == df,
miscresults$fmt_int(df, big.mark = big.mark), # integer version
formatC(
df,
format = "f",
digits = dp,
big.mark = big.mark,
decimal.mark = decimal.mark
) # floating-point version
))
}
miscresults$fmt_df_text <- function(
df_txt,
df_format = miscresults$DF_FORMAT_OPTIONS
) {
df_format <- match.arg(df_format)
if (df_format == "subscript") {
return(miscresults$subscript_(df_txt))
} else if (df_format == "roundbracket") {
return(sprintf("(%s)", df_txt))
} else { # squarebracket
return(sprintf("[%s]", df_txt))
}
}
miscresults$fmt_pct <- function(
proportion,
include_trailing_zero = FALSE,
na_str = get_flextable_defaults()$na_str,
nan_str = get_flextable_defaults()$nan_str
) {
# Format a proportion (e.g. 0.5) as a percentage (e.g. "50%").
pct <- 100 * proportion
txt <- paste0(
miscresults$fmt_float(
pct,
allow_sci_notation = FALSE,
include_trailing_zero = include_trailing_zero
),
"%"
)
return(case_when(
is.nan(proportion) ~ nan_str,
is.na(proportion) ~ na_str,
.default = txt
))
}
miscresults$fmt_n_percent <- function(
n,
proportion,
na_str = get_flextable_defaults()$na_str,
...
) {
# Format a number and a proportion as "n (x%)", where x is the percentage
# form of the proportion. As for flextable::fmt_n_percent, but emphasizes
# significant figures rather than decimal places for the percentage.
#
# Additional parameters are passed to fmt_pct().
ifelse(
is.na(n) | is.na(proportion),
na_str,
paste0(
miscresults$fmt_int(n),
" (",
miscresults$fmt_pct(proportion, ...),
")"
)
)
}
miscresults$mk_n_percent <- function(
n,
total,
min_threshold = NA,
less_than_symbol = "< ",
...
) {
# Format a number as "n (x%)", where x is the percentage form of n / total.
# - min_threshold: if specified (not NA), numbers below this are replaced
# by "<[threshold]", and similarly for percentages (small number
# suppression)
# - Additional parameters are passed to fmt_n_percent().
proportion <- n / total
return(ifelse(
!is.na(min_threshold) & n < min_threshold,
paste0(
less_than_symbol,
miscresults$fmt_int(min_threshold),
" (",
less_than_symbol,
miscresults$fmt_pct(min_threshold / total, ...),
")"
), # with small-number suppression
miscresults$fmt_n_percent(n, proportion, ...) # unsuppressed
))
}
miscresults$fmt_n_percent_low_high <- function(
n_low, n_high, total,
range_sep = " to ",
# ... an en dash is feasible but does break when using scientific notation
# and is a little confusing if there are also minus signs.
na_str = get_flextable_defaults()$na_str,
...
) {
# Format a number as "n_low-n_high (x-y%)": a "vague" version of
# mk_n_percent that can be used for small-number suppression for totals.
# For example, if you have group sizes A=50, B=50, C=<10, then the total is
# 100-109.
# - The percentages are n_low/total and n_high/total.
# - Additional parameters are passed to fmt_pct().
prop_low <- n_low / total
prop_high <- n_high / total
ifelse(
is.na(n_low) | is.na(n_high) | is.na(prop_low) | is.na(prop_high),
na_str,
paste0(
miscresults$fmt_int(n_low),
range_sep,
miscresults$fmt_int(n_high),
" (",
miscresults$fmt_pct(prop_low, ...),
range_sep,
miscresults$fmt_pct(prop_high, ...),
")"
)
)
}
miscresults$fmt_value_sd <- function(
x,
sigma,
sf = get_flextable_defaults()$digits,
allow_sci_notation = TRUE,
value_prefix = "",
# sd_prefix = paste0(" (", miscresults$PLUS_MINUS, " "),
sd_prefix = " (SD ",
sd_suffix = ")",
na_str = get_flextable_defaults()$na_str
) {
# Given a value x and a standard deviation sigma, show this as "x (± σ)",
# or similar.
# See also flextable::fmt_avg_dev(avg, dev), which is less flexible.
x_text <- miscresults$fmt_float(
x, sf = sf, allow_sci_notation = allow_sci_notation
)
s_text <- miscresults$fmt_float(
sigma, sf = sf, allow_sci_notation = allow_sci_notation
)
results <- paste0(value_prefix, x_text, sd_prefix, s_text, sd_suffix)
return(ifelse(is.na(x), na_str, results))
}
miscresults$mk_mean_sd <- function(
x,
na.rm = TRUE,
...
) {
# Calculate a mean and standard deviation (SD) from the vector provided, and
# show this as "μ (± σ)", or similar. Additional parameters are passed to
# fmt_value_sd().
return(miscresults$fmt_value_sd(
x = mean(x, na.rm = na.rm),
sigma = sd(x, na.rm = na.rm),
...
))
}
miscresults$fmt_value_ci <- function(
x,
ci_lower,
ci_upper,
value_prefix = "",
ci_prefix = " (CI ",
ci_sep = " to ", # miscresults$EN_DASH also possible
ci_suffix = ")",
sf = get_flextable_defaults()$digits,
allow_sci_notation = TRUE,
na_str = get_flextable_defaults()$na_str,
... # passed to fmt_float
) {
# Given a value x and confidence interval limits ci_lower, ci_upper, show
# this as e.g. "x (a–b)".
results <- paste0(
value_prefix,
miscresults$fmt_float(
x,
sf = sf, allow_sci_notation = allow_sci_notation, ...
),
ci_prefix,
miscresults$fmt_float(
ci_lower,
sf = sf, allow_sci_notation = allow_sci_notation, ...
),
ci_sep,
miscresults$fmt_float(
ci_upper,
sf = sf, allow_sci_notation = allow_sci_notation, ...
),
ci_suffix
)
return(ifelse(is.na(x), na_str, results))
}
miscresults$mk_mean_ci <- function(
x,
ci = miscresults$DEFAULT_CI,
na.rm = TRUE,
...
) {
# From a vector, show a mean and confidence interval (e.g. 95% CI) as e.g.
# "μ (a–b)". Additional parameters are passed to fmt_value_ci().
mu <- mean(x, na.rm = na.rm)
ci_pair <- miscstat$confidence_interval_t(x, ci = ci, na.rm = na.rm)
ci_lower <- ci_pair["ci_lower"]
ci_upper <- ci_pair["ci_upper"]
return(miscresults$fmt_value_ci(
x = mu,
ci_lower = ci_lower,
ci_upper = ci_upper,
...
))
}
miscresults$fmt_median_range <- function(
med,
range_lower,
range_upper,
median_prefix = "median ",
range_prefix = " (range ",
range_sep = " to ",
# ... an en dash is feasible but does break when using scientific notation
# and is a little confusing if there are also minus signs.
range_suffix = ")",
sf = get_flextable_defaults()$digits,
allow_sci_notation = TRUE,
na_str = get_flextable_defaults()$na_str
) {
# Given a median and range limits, this as e.g. "m (a–b)".
# Remember to think in parallel.
all_three_integer <- (
miscresults$is.wholenumber(range_lower)
& miscresults$is.wholenumber(range_lower)
& miscresults$is.wholenumber(range_upper)
)
formatter <- function(x) {
ifelse(
all_three_integer,
miscresults$fmt_int(x),
miscresults$fmt_float(
x,
sf = sf, allow_sci_notation = allow_sci_notation
)
)
}
median_text <- formatter(med)
range_lower_text <- formatter(range_lower)
range_upper_text <- formatter(range_upper)
results <- paste0(
median_prefix,
median_text,
range_prefix,
range_lower_text,
range_sep,
range_upper_text,
range_suffix
)
return(ifelse(is.na(med), na_str, results))
}
miscresults$mk_median_range <- function(
x,
na.rm = TRUE,
...
) {
# From a vector, show a median and range as e.g. "m (a–b)". Additional
# parameters are passed to fmt_median_range().
med <- median(x, na.rm = na.rm)
range_lower <- min(x, na.rm = na.rm)
range_upper <- max(x, na.rm = na.rm)
return(miscresults$fmt_median_range(
med = med,
range_lower = range_lower,
range_upper = range_upper,
...
))
}
miscresults$fmt_chisq <- function(
chisq, df,
min_chisq = 1, # minimum value shown exactly
# ... critical value is qchisq(0.95, df) at α=0.05 and df=1, increasing
# for higher df. We might want to report things that didn't
# make it, but 1 seems like a reasonable "definitely do not care"
# threshold.
df_format = miscresults$DF_FORMAT_OPTIONS
) {
# Format a chi-square statistic (without a p value).
# - Note that chi-square can only be positive.
df_txt <- miscresults$fmt_df_text(
miscresults$mk_df_text(df),
df_format = df_format
)
symbol_df_txt <- paste0(
miscresults$italic_(miscresults$CHI_LOWER),
miscresults$superscript_("2"),
df_txt
)
return(ifelse(
chisq < min_chisq,
sprintf("%s < %s", symbol_df_txt, min_chisq),
sprintf("%s = %s", symbol_df_txt, miscresults$fmt_float(chisq))
))
}
miscresults$fmt_chisq_p <- function(
chisq, df, p,
min_chisq = 1, # see miscresults$fmt_chisq()
ns_text = miscresults$NOT_SIGNIFICANT,
check_alpha = DEFAULT_ALPHA,
df_format = miscresults$DF_FORMAT_OPTIONS
) {
# Format a chi-square statistic with a p value).
chisq_txt <- miscresults$fmt_chisq(
chisq, df,
min_chisq = min_chisq, df_format = df_format
)
p_txt <- miscresults$mk_p_text_with_label(p, ns_text = ns_text)
if (any(chisq < min_chisq & p < check_alpha)) {
stop(sprintf(
"chisq (%f) < %f but p = %f so disallowing visual shortcut",
chisq, min_chisq, p
))
}
return(ifelse(
chisq < min_chisq,
sprintf("%s, %s", chisq_txt, ns_text),
sprintf("%s, %s", chisq_txt, p_txt)
))
}
miscresults$fmt_t <- function(
t, df,
min_abs_t = miscresults$MINIMUM_ABS_T_SHOWN,
omit_df_below_min_t = miscresults$DEFAULT_OMIT_DF_BELOW_MIN_STATS,
df_format = miscresults$DF_FORMAT_OPTIONS
) {
# Format a t statistic (without a p value).
# - Note that t can be negative or positive.
df_txt <- ifelse(
is.na(df),
"",
miscresults$fmt_df_text(
miscresults$mk_df_text(df),
df_format = df_format
)
)
t_txt <- miscresults$fmt_float(t, use_plus = TRUE)
italic_t <- miscresults$italic_("t")
min_abs_t_txt <- as.character(min_abs_t)
return(ifelse(
abs(t) < min_abs_t,
ifelse(
omit_df_below_min_t,
paste0(miscresults$abs_(italic_t), " < ", min_abs_t_txt),
paste0(
miscresults$abs_(paste0(italic_t, df_txt)),
" < ", min_abs_t_txt
)
),
paste0(italic_t, df_txt, " = ", t_txt)
))
}
miscresults$fmt_t_p <- function(
t, df, p,
min_abs_t = miscresults$MINIMUM_ABS_T_SHOWN,
omit_df_below_min_t = miscresults$DEFAULT_OMIT_DF_BELOW_MIN_STATS,
ns_text = miscresults$NOT_SIGNIFICANT,
check_alpha = DEFAULT_ALPHA,
df_format = miscresults$DF_FORMAT_OPTIONS
) {
# Format a t statistic with a p value.
t_txt <- miscresults$fmt_t(
t, df,
min_abs_t = min_abs_t,
omit_df_below_min_t = omit_df_below_min_t,
df_format = df_format
)
p_txt <- miscresults$mk_p_text_with_label(p, ns_text = ns_text)
if (any(abs(t) < min_abs_t & p < check_alpha)) {
stop(sprintf(
"|t| (|%f|) < %f but p = %f so disallowing visual shortcut",
t, min_abs_t, p
))
}
return(ifelse(
abs(t) < min_abs_t,
sprintf("%s, %s", t_txt, ns_text),
sprintf("%s, %s", t_txt, p_txt)
))
}
miscresults$fmt_F <- function(
F, df1, df2,
min_F = miscresults$MINIMUM_F_SHOWN,
omit_df_below_min_F = miscresults$DEFAULT_OMIT_DF_BELOW_MIN_STATS,
df_format = miscresults$DF_FORMAT_OPTIONS
) {
# Format an F statistic (without a p value).
# - Note that F will always be positive.
# - No commas in degrees of freedom (big.mark = ""), since they are
# separated by commas anyway.
df1_txt <- miscresults$mk_df_text(df1, big.mark = "")
df2_txt <- miscresults$mk_df_text(df2, big.mark = "")
df_txt <- miscresults$fmt_df_text(
sprintf("%s,%s", df1_txt, df2_txt),
df_format = df_format
)
italic_F <- miscresults$italic_("F")
return(ifelse(
F < min_F,
ifelse(
omit_df_below_min_F,
sprintf("%s < %s", italic_F, min_F),
sprintf("%s%s < %s", italic_F, df_txt, min_F)
),
paste0(italic_F, df_txt, " = ", miscresults$fmt_float(F))
))
}
miscresults$fmt_F_p <- function(
F, df1, df2, p,
min_F = miscresults$MINIMUM_F_SHOWN,
omit_df_below_min_F = miscresults$DEFAULT_OMIT_DF_BELOW_MIN_STATS,
ns_text = miscresults$NOT_SIGNIFICANT,
check_alpha = DEFAULT_ALPHA,
df_format = miscresults$DF_FORMAT_OPTIONS
) {
# Format an F statistic with a p value.
f_txt <- miscresults$fmt_F(
F, df1, df2,
min_F = min_F,
omit_df_below_min_F = omit_df_below_min_F,
df_format = df_format
)
p_txt <- miscresults$mk_p_text_with_label(p, ns_text = ns_text)
if (any(F < min_F & p < check_alpha)) {
stop(sprintf(
"F (%f) < %f but p = %f so disallowing visual shortcut",
F, min_F, p
))
}
return(ifelse(
F < min_F,
sprintf("%s, %s", f_txt, ns_text), # e.g. "F[df1,df2] < 1, NS"
sprintf("%s, %s", f_txt, p_txt) # e.g. "F[df1,df2] = 5, p = ..."
))
}
miscresults$fmt_Z <- function(Z, use_plus = TRUE) {
# Format a Z statistic (without a p value).
z_txt <- miscresults$fmt_float(Z, use_plus = use_plus)
return(paste0(
miscresults$italic_("Z"),
" = ",
z_txt
))
}
miscresults$fmt_Z_p <- function(
Z, p,
use_plus = TRUE,
ns_text = miscresults$NOT_SIGNIFICANT
) {
# Format a Z statistic with a p value.
z_txt <- miscresults$fmt_Z(Z, use_plus = use_plus)
p_txt <- miscresults$mk_p_text_with_label(p, ns_text = ns_text)
return(paste0(z_txt, ", ", p_txt))
}
miscresults$fmt_predictor <- function(
predictor_txt,
replacements = NULL, # e.g. c("from1" = "to1", "from1" = "to2", ...)
interaction_txt = paste0(" ", miscresults$MULTIPLY, " ")
) {
# Format a predictor nicely, e.g. changing "drug:sex" to "Drug x Sex".
predictor_txt <- stringr::str_replace_all(