Repository navigation
Expand file tree
/
Copy pathutils.R
More file actions
6592 lines (5987 loc) · 249 KB
/
Copy pathutils.R
File metadata and controls
6592 lines (5987 loc) · 249 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' Calculate Hedges' g using means and standard deviations
#'
#' Calculate Hedges' g using Mean and Standard Deviation. Only meant to be used as
#' part of \code{\link{calculateEffectSizes}}.
#'
#' @param x data
#' @param ... Effect size data. Data frame must include columns `mean_arm1`, `mean_arm2`,
#' `sd_arm1`, `sd_arm2`, `n_arm1`, `n_arm2`. See the [Metapsy data standard](https://docs.metapsy.org/data-preparation/format/).
#' @usage g.m.sd(x, ...)
#' @importFrom dplyr select
#' @importFrom purrr pmap_dfr
#' @importFrom esc esc_mean_sd
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @export g.m.sd
#' @keywords internal
g.m.sd = function(x, ...){
x %>%
purrr::pmap_dfr(function(mean_arm1, mean_arm2, sd_arm1,
sd_arm2, n_arm1, n_arm2, ...)
{esc::esc_mean_sd(mean_arm1, sd_arm1, n_arm1,
mean_arm2, sd_arm2, n_arm2, es.type = "g") %>%
as.data.frame() %>% dplyr::select(es, se) %>%
suppressWarnings()})
}
#' Calculate Hedges' g using binary outcome data
#'
#' Calculates Hedges' g from binary outcome data. Only meant to be used as
#' part of \code{\link{calculateEffectSizes}}.
#'
#' @param x data
#' @param cc Should a continuity correction for zero cells be applied?
#' Either `TRUE` (default; applies the Sweeting et al. (2004) treatment-arm
#' continuity correction, TACC), `FALSE` (no correction), or a single numeric
#' increment to be added to all four cells (e.g., `0.5`).
#' @param ... Binary effect size data. Data frame must include columns `event_arm1`, `event_arm2`,
#' `totaln_arm1`, `totaln_arm2`. See the [Metapsy data standard](https://docs.metapsy.org/data-preparation/format/).
#' @usage g.binary(x, cc = TRUE, ...)
#' @importFrom dplyr select mutate
#' @importFrom purrr pmap_dfr
#' @importFrom esc esc_2x2
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @export g.binary
#' @keywords internal
g.binary = function(x, cc = TRUE, ...){
if (identical(cc, FALSE)){
x %>%
purrr::pmap_dfr(function(event_arm1, event_arm2,
totaln_arm1, totaln_arm2, ...)
{esc::esc_2x2(event_arm1,
totaln_arm1 - event_arm1,
event_arm2,
totaln_arm2 - event_arm2,
es.type = "g") %>%
as.data.frame() %>% dplyr::select(es, se) %>%
suppressWarnings() %>%
dplyr::mutate(es = es*-1)})
} else {
x %>%
purrr::pmap_dfr(function(event_arm1, event_arm2,
totaln_arm1, totaln_arm2, ...)
{
# Basic guards
if (any(is.na(c(event_arm1, event_arm2, totaln_arm1, totaln_arm2))) ||
!all(c(totaln_arm1, totaln_arm2) > 0) ||
event_arm1 < 0 || event_arm2 < 0 ||
event_arm1 > totaln_arm1 || event_arm2 > totaln_arm2) {
return(data.frame(es = NA_real_, se = NA_real_))
}
nonevent_arm1 <- totaln_arm1 - event_arm1
nonevent_arm2 <- totaln_arm2 - event_arm2
use_cc <- (event_arm1 == 0 || event_arm2 == 0 || nonevent_arm1 == 0 || nonevent_arm2 == 0)
a <- event_arm1; b <- nonevent_arm1
c <- event_arm2; d <- nonevent_arm2
if (isTRUE(cc) && use_cc) {
# Sweeting et al. (2004) treatment-arm continuity correction (TACC)
n1 <- totaln_arm1
n2 <- totaln_arm2
k1 <- n2 / (n1 + n2)
k2 <- n1 / (n1 + n2)
a <- a + k1; b <- b + k1
c <- c + k2; d <- d + k2
} else if (use_cc) {
cc_val <- cc
if (!is.numeric(cc_val) || length(cc_val) != 1 || is.na(cc_val)) cc_val <- 0.5
a <- a + cc_val; b <- b + cc_val
c <- c + cc_val; d <- d + cc_val
}
esc::esc_2x2(a, b, c, d, es.type = "g") %>%
as.data.frame() %>%
dplyr::select(es, se) %>%
suppressWarnings() %>%
dplyr::mutate(es = es * -1)
})
}
}
#' Forward pre-calculated values of Hedges' g
#'
#' Forwards pre-calculated values of Hedges' g. Only meant to be used as
#' part of \code{\link{calculateEffectSizes}}.
#'
#' @param x data
#' @param ... Pre-calculated effect size data. Data frame must include columns \code{precalc_g} and
#' \code{precalc_g_se}. See the [Metapsy data standard](https://docs.metapsy.org/data-preparation/format/).
#' @usage g.precalc(x, ...)
#' @importFrom purrr pmap_dfr
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @export g.precalc
#' @keywords internal
g.precalc = function(x, ...){
if (is.null(x$precalc_g) | is.null(x$precalc_g_se)){
return(data.frame(es = NA, se = NA))
}
x %>%
purrr::pmap_dfr(function(precalc_g, precalc_g_se, ...)
{data.frame(es = precalc_g, se = precalc_g_se) %>%
suppressWarnings()})
}
#' Forward pre-calculated log-risk ratios
#'
#' Forwards pre-calculated log-risk ratios. Only meant to be used as
#' part of \code{\link{calculateEffectSizes}}.
#'
#' @param x data
#' @param ... Pre-calculated effect size data. Data frame must include columns
#' \code{precalc_log_rr} and \code{precalc_log_rr_se}. See the [Metapsy data standard](https://docs.metapsy.org/data-preparation/format/).
#' @usage rr.precalc(x, ...)
#' @importFrom purrr pmap_dfr
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @export rr.precalc
#' @keywords internal
rr.precalc = function(x, ...){
if (is.null(x$precalc_log_rr) | is.null(x$precalc_log_rr_se)){
return(data.frame(es = NA, se = NA))
}
x %>%
purrr::pmap_dfr(function(precalc_log_rr, precalc_log_rr_se, ...)
{data.frame(es = precalc_log_rr, se = precalc_log_rr_se) %>%
suppressWarnings()})
}
#' Calculate the log-risk ratio using binary outcome data
#'
#' Calculate the log risk ratio using binary outcome data. Only meant to be used as
#' part of \code{\link{calculateEffectSizes}}.
#'
#' @param x data
#' @param cc `logical`. Should a continuity correction for zero cells be applied?
#' `TRUE` (default, applies the TACC correction) or `FALSE` (no correction).
#' @param ... Binary effect size data. Data frame must include columns `event_arm1`, `event_arm2`,
#' `totaln_arm1`, `totaln_arm2`. See the [Metapsy data standard](https://docs.metapsy.org/data-preparation/format/).
#' @usage rr.binary(x, cc = TRUE, ...)
#' @details When `cc = TRUE`, a treatment-arm continuity correction (TACC) is applied
#' when any cell in the 2x2 table has zero count. Following
#' [Sweeting et al. (2004)](https://doi.org/10.1002/sim.1761), a correction of
#' `k = n_opposite / (n_arm1 + n_arm2)` is added to both cells of each arm
#' (i.e., `totaln_arm2 / (totaln_arm1 + totaln_arm2)` to the arm1 cells and
#' `totaln_arm1 / (totaln_arm1 + totaln_arm2)` to the arm2 cells) before
#' calculating `es` and `se`. The correction is not applied to the stored
#' cell counts. When arms are balanced this reduces to adding 0.5 to all
#' cells, but unlike a fixed 0.5 correction it remains unbiased under
#' unequal arm sizes.
#' @importFrom dplyr select mutate
#' @importFrom purrr pmap_dfr
#' @importFrom esc esc_2x2
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @export rr.binary
#' @keywords internal
rr.binary = function(x, cc = TRUE, ...){
if (!isTRUE(cc)){
x %>%
purrr::pmap_dfr(function(event_arm1, event_arm2,
totaln_arm1, totaln_arm2, ...)
{data.frame(es = log((event_arm1/totaln_arm1)/
(event_arm2/totaln_arm2)),
se = sqrt((1/event_arm1) + (1/event_arm2) -
(1/totaln_arm1) - (1/totaln_arm2)),
.event_arm1 = event_arm1,
.event_arm2 = event_arm2,
.totaln_arm1 = totaln_arm1,
.totaln_arm2 = totaln_arm2) %>%
suppressWarnings()})
} else {
x %>%
purrr::pmap_dfr(function(event_arm1, event_arm2,
totaln_arm1, totaln_arm2, ...)
{
# Basic guards: totals must be positive; events must be within [0, total]
if (any(is.na(c(event_arm1, event_arm2, totaln_arm1, totaln_arm2))) ||
!all(c(totaln_arm1, totaln_arm2) > 0) ||
event_arm1 < 0 || event_arm2 < 0 ||
event_arm1 > totaln_arm1 || event_arm2 > totaln_arm2) {
return(data.frame(es = NA_real_, se = NA_real_,
.event_arm1 = event_arm1,
.event_arm2 = event_arm2,
.totaln_arm1 = totaln_arm1,
.totaln_arm2 = totaln_arm2))
}
nonevent_arm1 = totaln_arm1 - event_arm1
nonevent_arm2 = totaln_arm2 - event_arm2
e1 = event_arm1
e2 = event_arm2
n1 = totaln_arm1
n2 = totaln_arm2
# Apply TACC whenever any cell is zero
use_tacc <- (e1 == 0 || e2 == 0 || nonevent_arm1 == 0 || nonevent_arm2 == 0)
if (use_tacc) {
# Treatment-arm continuity correction (Sweeting et al., 2004)
k1 = n2 / (n1 + n2)
k2 = n1 / (n1 + n2)
e1 = e1 + k1
e2 = e2 + k2
n1 = n1 + 2 * k1
n2 = n2 + 2 * k2
}
data.frame(
es = log((e1 / n1) / (e2 / n2)),
se = sqrt((1 / e1) + (1 / e2) - (1 / n1) - (1 / n2)),
.event_arm1 = event_arm1,
.event_arm2 = event_arm2,
.totaln_arm1 = totaln_arm1,
.totaln_arm2 = totaln_arm2
) %>%
suppressWarnings()
})
}
}
#' Calculate Hedges' g using within-group change data
#'
#' Calculate Hedges' g based on change data. Only meant to be used as
#' part of \code{\link{calculateEffectSizes}}.
#'
#' @param x data
#' @param ... Change score effect size data. Data frame must include columns `mean_change_arm1`,
#' `mean_change_arm2`, `sd_change_arm1`, `sd_change_arm2`,
#' `n_change_arm1`, `n_change_arm2`. See the [Metapsy data standard](https://docs.metapsy.org/data-preparation/format/).
#' @usage g.change.m.sd(x, ...)
#' @importFrom dplyr select
#' @importFrom purrr pmap_dfr
#' @importFrom esc esc_mean_sd
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @export g.change.m.sd
#' @keywords internal
g.change.m.sd = function(x, ...){
x %>%
purrr::pmap_dfr(function(mean_change_arm1, mean_change_arm2, sd_change_arm1,
sd_change_arm2, n_change_arm1, n_change_arm2, ...)
{esc::esc_mean_sd(mean_change_arm1, sd_change_arm1, n_change_arm1,
mean_change_arm2, sd_change_arm2, n_change_arm2,
es.type = "g") %>%
as.data.frame() %>% dplyr::select(es, se) %>%
suppressWarnings()})
}
#' Calculate the log ratio of means (ROM) using means and standard deviations
#'
#' Computes the natural log-transformed ratio of means (log ROM, also called the
#' log response ratio) and its standard error using the delta method. This is an
#' internal helper called row-wise by \code{\link{calculateEffectSizes}} and is
#' not intended to be used directly.
#'
#' The log ROM effect size is defined as:
#' \deqn{\ln(\text{ROM}) = \ln\!\left(\frac{\bar{x}_1}{\bar{x}_2}\right)}
#'
#' Its sampling variance is approximated via the delta method (Hedges et al., 1999):
#' \deqn{v = \frac{s_1^2}{n_1 \bar{x}_1^2} + \frac{s_2^2}{n_2 \bar{x}_2^2}}
#'
#' The standard error returned in \code{se} is \eqn{\sqrt{v}}.
#'
#' A positive log ROM indicates that arm 1 has a higher mean than arm 2.
#' The measure is undefined when either group mean equals zero, which is why
#' such rows are returned as \code{NA}.
#'
#' @param x A \code{data.frame} in which each row represents one trial arm
#' comparison. Must contain the columns listed under \code{...}.
#' @param ... The following columns are required and consumed from \code{x}:
#' \describe{
#' \item{\code{mean_arm1}}{Mean of the outcome in arm 1 (treatment).}
#' \item{\code{mean_arm2}}{Mean of the outcome in arm 2 (control/comparator).}
#' \item{\code{sd_arm1}}{Standard deviation of the outcome in arm 1.}
#' \item{\code{sd_arm2}}{Standard deviation of the outcome in arm 2.}
#' \item{\code{n_arm1}}{Sample size of arm 1. Must be > 0.}
#' \item{\code{n_arm2}}{Sample size of arm 2. Must be > 0.}
#' }
#' Additional columns in \code{x} are silently ignored.
#'
#' @return A \code{data.frame} with the same number of rows as \code{x} and
#' two numeric columns:
#' \describe{
#' \item{\code{es}}{Log ratio of means, \eqn{\ln(\bar{x}_1 / \bar{x}_2)}.}
#' \item{\code{se}}{Standard error of \code{es}, derived via the delta method.}
#' }
#' Rows are set to \code{NA} for both columns when any required input is
#' \code{NA}, when either mean equals zero (log ROM is undefined), when
#' either sample size is non-positive, or when the computed variance is
#' non-finite or not strictly positive.
#'
#' @references
#' Hedges, L. V., Gurevitch, J., & Curtis, P. S. (1999). The meta-analysis
#' of response ratios in experimental ecology. *Ecology, 80*(4), 1150–1156.
#' \doi{10.1890/0012-9658(1999)080[1150:TMAORR]2.0.CO;2}
#'
#' Lajeunesse, M. J. (2011). On the meta-analysis of response ratios for
#' studies with correlated and multi-group designs. *Ecology, 92*(11),
#' 2049–2055. \doi{10.1890/11-0423.1}
#'
#' @seealso \code{\link{calculateEffectSizes}}
#' @export
#' @keywords internal
rom.m.sd = function(x, ...){
x %>%
purrr::pmap_dfr(function(mean_arm1, mean_arm2, sd_arm1, sd_arm2, n_arm1, n_arm2, ...){
m1 = mean_arm1; m2 = mean_arm2
s1 = sd_arm1; s2 = sd_arm2
n1 = n_arm1; n2 = n_arm2
if (is.na(m1) || is.na(m2) || m1 == 0 || m2 == 0 ||
is.na(s1) || is.na(s2) || is.na(n1) || is.na(n2) || n1 <= 0 || n2 <= 0)
return(data.frame(es = NA_real_, se = NA_real_))
log_rom = log(m1 / m2)
vi = (s1^2) / (n1 * m1^2) + (s2^2) / (n2 * m2^2)
if (!is.finite(vi) || vi <= 0) return(data.frame(es = NA_real_, se = NA_real_))
data.frame(es = log_rom, se = sqrt(vi))
})
}
#' Calculate the log ratio of means (ROM) using within-group change data
#'
#' Computes the natural log-transformed ratio of means (log ROM) and its
#' standard error using the delta method, based on pre-post change scores
#' rather than post-treatment means. This is an internal helper called
#' row-wise by \code{\link{calculateEffectSizes}} and is not intended to be
#' used directly.
#'
#' The estimator is identical in form to that used in \code{\link{rom.m.sd}},
#' but the inputs are mean change scores and their standard deviations:
#' \deqn{\ln(\text{ROM}) = \ln\!\left(\frac{\bar{x}_{\Delta,1}}{\bar{x}_{\Delta,2}}\right)}
#'
#' Its sampling variance is approximated via the delta method (Hedges et al., 1999):
#' \deqn{v = \frac{s_{\Delta,1}^2}{n_1 \,\bar{x}_{\Delta,1}^2} + \frac{s_{\Delta,2}^2}{n_2\, \bar{x}_{\Delta,2}^2}}
#'
#' The standard error returned in \code{se} is \eqn{\sqrt{v}}.
#'
#' A positive log ROM indicates a larger mean change in arm 1 than in arm 2.
#' The measure is undefined when either change-score mean equals zero, so
#' such rows are returned as \code{NA}. Note that a zero mean change score is
#' substantively meaningful (no average change from baseline) and relatively
#' common, so this limitation should be considered when choosing between
#' effect size metrics.
#'
#' @param x A \code{data.frame} in which each row represents one trial arm
#' comparison. Must contain the columns listed under \code{...}.
#' @param ... The following columns are required and consumed from \code{x}:
#' \describe{
#' \item{\code{mean_change_arm1}}{Mean change from baseline in arm 1 (treatment).}
#' \item{\code{mean_change_arm2}}{Mean change from baseline in arm 2 (control/comparator).}
#' \item{\code{sd_change_arm1}}{Standard deviation of the change score in arm 1.}
#' \item{\code{sd_change_arm2}}{Standard deviation of the change score in arm 2.}
#' \item{\code{n_arm1}}{Sample size of arm 1. Must be > 0.}
#' \item{\code{n_arm2}}{Sample size of arm 2. Must be > 0.}
#' }
#' Additional columns in \code{x} are silently ignored.
#'
#' @return A \code{data.frame} with the same number of rows as \code{x} and
#' two numeric columns:
#' \describe{
#' \item{\code{es}}{Log ratio of change-score means,
#' \eqn{\ln(\bar{x}_{\Delta,1} / \bar{x}_{\Delta,2})}.}
#' \item{\code{se}}{Standard error of \code{es}, derived via the delta method.}
#' }
#' Rows are set to \code{NA} for both columns when any required input is
#' \code{NA}, when either change-score mean equals zero (log ROM is
#' undefined), when either sample size is non-positive, or when the
#' computed variance is non-finite or not strictly positive.
#'
#' @references
#' Hedges, L. V., Gurevitch, J., & Curtis, P. S. (1999). The meta-analysis
#' of response ratios in experimental ecology. *Ecology, 80*(4), 1150–1156.
#' \doi{10.1890/0012-9658(1999)080[1150:TMAORR]2.0.CO;2}
#'
#' Lajeunesse, M. J. (2011). On the meta-analysis of response ratios for
#' studies with correlated and multi-group designs. *Ecology, 92*(11),
#' 2049–2055. \doi{10.1890/11-0423.1}
#'
#' @seealso \code{\link{rom.m.sd}} for the post-treatment mean variant;
#' \code{\link{calculateEffectSizes}} for the calling function.
#' @export
#' @keywords internal
rom.change.m.sd = function(x, ...){
x %>%
purrr::pmap_dfr(function(mean_change_arm1, mean_change_arm2, sd_change_arm1,
sd_change_arm2, n_change_arm1, n_change_arm2, ...){
m1 = mean_change_arm1; m2 = mean_change_arm2
s1 = sd_change_arm1; s2 = sd_change_arm2
n1 = n_change_arm1; n2 = n_change_arm2
if (is.na(m1) || is.na(m2) || m1 == 0 || m2 == 0 ||
is.na(s1) || is.na(s2) || is.na(n1) || is.na(n2) || n1 <= 0 || n2 <= 0)
return(data.frame(es = NA_real_, se = NA_real_))
log_rom = log(m1 / m2)
vi = (s1^2) / (n1 * m1^2) + (s2^2) / (n2 * m2^2)
if (!is.finite(vi) || vi <= 0) return(data.frame(es = NA_real_, se = NA_real_))
data.frame(es = log_rom, se = sqrt(vi))
})
}
#' Aggregate standard deviations of multiple trials
#'
#' This function allows you to aggregate standard deviations of outcome scores
#' across multiple trials.
#'
#' @details Values are aggregated assuming homogeneous variances across studies
#' (i.e., all trials share the same population standard deviation). The following
#' formula is used:
#'
#' \mjtdeqn{s_{\text{pooled}} = \sqrt{ \frac{ \sum (n_i - 1) \cdot s_i^2 }{ \sum (n_i - 1) } }}{s_{\text{pooled}} = \sqrt{ \frac{ \sum (n_i - 1) \cdot s_i^2 }{ \sum (n_i - 1) } }}{s_{\text{pooled}} = \sqrt{ \frac{ \sum (n_i - 1) \cdot s_i^2 }{ \sum (n_i - 1) } }}
#'
#' where \mjeqn{s_i}{s_i} and \mjeqn{n_i}{n_i} are the standard deviation and
#' sample size in some study \mjeqn{i}{i}. Please note that aggregation is only
#' possible when all SD values come from the same scale or instrument.
#'
#' @usage aggregateSD(sd, n, ...)
#' @param sd A numeric vector of standard deviations.
#' @param n A numeric vector of sample sizes corresponding to each standard deviation.
#' @param ... Additional arguments (not used).
#' @return The pooled standard deviation across trials.
#' @export aggregateSD
#' @keywords internal
#' @examples
#' \dontrun{
#' sd <- c(8.77, 9.01, 10.11)
#' n <- c(120, 15, 80)
#' aggregateSD(sd, n)
#' }
aggregateSD = function(sd, n, ...) {
if (length(sd) != length(n))
stop("Vectors 'sd' and 'n' must be the same length.")
return(sqrt((sum((n - 1) * sd^2))/(sum(n - 1))))
}
#' Calculate NNTs
#'
#' Calculate NNTs (extracted from \code{dmetar})
#'
#' @param d A single numeric or concatenated vector of numerics representing the effect size expressed as
#' Cohen's \eqn{d} or Hedges' \eqn{g}. If this is the only parameter specified in the function, the method by
#' Kraemer and Kupfer is used automatically to calculate \eqn{NNT}s.
#' @param CER The control group event ratio. Furukawa's method (Furukawa & Leucht, 2011) to calculate \code{NNT}s
#' from \code{d} requires that the assumed response ("event") ratio in the control group (\eqn{\frac{n_{responders}}{N_{total}}})
#' is specified. The CER can assume values from 0 to 1. If a value is specified for \code{CER}, Furukawa's method is
#' used automatically. Argument \code{method} has to be set to \code{"KraemerKupfer"} to override this.
#' @param event.e Single number or numeric vector. The number of (favourable) events in the experimental group.
#' @param n.e Single number or numeric vector. The number participants in the experimental group.
#' @param event.c Single number or numeric vector. The number of (favourable) events in the control group.
#' @param n.c Single number or numeric vector. The number of participants in the control group.
#' @param RR Optional. A single numeric or vector of numeric risk ratios. When supplied,
#' NNT is calculated from \code{RR} and \code{CER} via \eqn{NNT = 1 / |CER * (RR - 1)|}.
#' This requires \code{CER} to be provided as a numeric value between 0 and 1.
#' @param names Optional. Character vector of equal length as the vector supplied to \code{d} or \code{event.e} containing
#' study/effect size labels.
#' @param method The method to be used to calculate the NNT from \code{d}. Either \code{"KraemerKupfer"} for the
#' method proposed by Kraemer and Kupfer (2006) or \code{"Furukawa"} for the Furukawa method (Furukawa & Leucht, 2011).
#' Please note that the Furukawa's method can only be used when \code{CER} is specified.
#' @usage metapsyNNT(d, CER, event.e, n.e, event.c, n.c, RR, names, method)
#' @export metapsyNNT
#' @keywords internal
metapsyNNT = function(d, CER = NULL, event.e = NULL, n.e = NULL, event.c = NULL,
n.c = NULL, RR = NULL, names = NULL, method = NULL)
{
if (!missing(CER) & is.numeric(CER)) {
if (sum(CER < 0 | CER > 1) > 0) {
stop("'CER' range must be between 0 and 1.")
}
}
if (!missing(RR)) {
if (missing(CER) || !is.numeric(CER) || any(CER < 0 | CER > 1)) {
stop("To use RR-based NNT, provide numeric 'CER' in the range [0, 1].")
}
if (!is.numeric(RR)) {
stop("'RR' must be numeric.")
}
if (any(RR <= 0, na.rm = TRUE)) {
stop("'RR' must be > 0.")
}
arr <- CER * (RR - 1)
NNT <- abs(1 / arr)
NNT[arr == 0] <- Inf
class(NNT) = c("NNT", "rr", "numeric")
} else if (missing(event.e)) {
if (missing(CER)) {
NNT = 1/((2 * pnorm(d/sqrt(2)) - 1))
class(NNT) = c("NNT", "kk", "numeric")
}
else {
if (missing(method)) {
NNT = 1/(pnorm(d + qnorm(CER)) - CER)
class(NNT) = c("NNT", "fl", "numeric")
}
else {
if (method == "KraemerKupfer") {
NNT = 1/((2 * pnorm(d/sqrt(2)) - 1))
class(NNT) = c("NNT", "kk", "numeric")
}
else {
}
if (method == "Furukawa") {
if (missing(CER) | !inherits(CER, "numeric")) {
stop("To use Furukawa's method, provide a numeric value for CER. \n")
}
else {
NNT = 1/(pnorm(d + qnorm(CER)) - CER)
class(NNT) = c("NNT", "fl", "numeric")
}
}
else {
}
}
}
} else {
if (inherits(event.e, "numeric") & missing(d)) {
EER = event.e/n.e
CER = event.c/n.c
NNT = abs(1/(EER - CER))
class(NNT) = c("NNT", "raw", "numeric")
if (missing(method)) {
}
else {
if (method %in% c("KraemerKupfer", "Furukawa")) {
class(NNT) = c("NNT", "unspecified", "numeric")
}
else {
}
}
}
}
if (missing(names)) {
return(NNT)
}
else {
data = data.frame(Name = names, NNT = NNT)
class(data) = c(class(NNT)[1:2], "data.frame")
class(data$NNT) = "numeric"
NNT = data
return(NNT)
}
}
#' Expander function for multiarm trials
#'
#' Expands multiarm trial.
#'
#' @param study data of one study, for one unique assessment point.
#' @param condition.specification trial condition specification.
#' @param group.indicator group indicator (IG or CG).
#' @param group.names group names (list).
#' @export multiarmExpander
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @keywords internal
multiarmExpander = function(study,
condition.specification,
group.indicator,
group.names){
# Replace missings with empty char
study[[condition.specification]][is.na(study[[condition.specification]])] = "N/A"
# Get combination of study arms
varType = study[[group.indicator]]
names(varType) = study[[condition.specification]]
utils::combn(study[[condition.specification]], 2,
simp = FALSE) -> combinations
# Expand by looping through all combinations;
# IGs come first if compared to CGs
trialExpand = list()
for (i in 1:length(combinations)){
if (varType[[combinations[[i]][1]]] == group.names[["cg"]] &
varType[[combinations[[i]][2]]] == group.names[["ig"]]){
rbind(study[study[[condition.specification]] == combinations[[i]][2],],
study[study[[condition.specification]] == combinations[[i]][1],]) -> trial
} else {
rbind(study[study[[condition.specification]] == combinations[[i]][1],],
study[study[[condition.specification]] == combinations[[i]][2],]) -> trial
}
trial$trt = c("trt1", "trt2")
trial$id = paste0(trial$id, "_", paste(combinations[[i]], collapse = "_"))
trialExpand[[i]] = trial
}
do.call(rbind, trialExpand) -> res
return(res)
}
#' String detection wrapper
#'
#' Wrapper for \code{str_detect} in the \code{stringr} package.
#'
#' @param ... Arguments passed to \code{str_detect}.
#' @usage Detect(...)
#' @export Detect
#' @importFrom stringr str_detect
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @keywords internal
Detect = function(...){
stringr::str_detect(...)
}
#' Include information of rows with switched reference group
#'
#' Adds effect size data and study information of rows with switched reference arms.
#'
#' @param dat Data set created by \code{calculateEffectSizes} in the wider format, which includes
#' calculated effect sizes and standard errors in columns \code{es} and \code{se}, respectively. Only
#' data sets created by \code{calculateEffectSizes} with \code{trt.indicator} set to \code{"trt"}
#' can be used.
#' @param ... Further arguments (not used).
#' @usage includeSwitchedArms(dat, ...)
#' @export includeSwitchedArms
#' @importFrom stringr str_replace_all
#' @importFrom dplyr mutate select
#' @importFrom stats dffits model.matrix rnorm rstudent
#' @importFrom utils combn
#' @keywords internal
includeSwitchedArms = function(dat, ...){
dat.orig = dat
stringr::str_replace_all(colnames(dat),
c("_arm1" = "_armX", "_arm2" = "_arm1",
"_armX" = "_arm2")) -> colnames(dat)
dat %>% dplyr::select(colnames(dat.orig)) %>%
dplyr::mutate(.g = .g*-1,
.log_rr = .log_rr*-1,
.id = paste0(.id, "_arm_switched")) %>%
rbind(., dat.orig) -> dat.expand
dat.expand = dat.expand[order(dat.expand$.id),]
rownames(dat.expand) = NULL
return(dat.expand)
}
#' `tryCatch` alternative that saves the error message
#'
#' @param expr R expression.
#' @usage tryCatch2(expr)
#' @export
#' @keywords internal
tryCatch2 = function(expr) {
warn = err = NULL
value = withCallingHandlers(
tryCatch(expr, error=function(e) {
err <<- e
NULL
}), warning=function(w) {
warn <<- w
invokeRestart("muffleWarning")
})
list(value=value, warning=warn,
error=err, has.error = is.null(value))
}
#' Collapse signalling question ratings
#' @keywords internal
collapseRatings = function(x, var){
x[[var]] -> r.rating
if ((var %in% c("d4_16", "d4_17")) &
length(r.rating > 1) &
("Yes/PY" %in% r.rating)) { "Yes/PY" } else {
prio = c("No/PN" = 3, "NI" = 2, "Yes/PY" = 1)
suppressWarnings(names(
which(prio==max(prio[unique(r.rating)], na.rm = T)))) -> r.new
ifelse(length(r.new)>0, r.new, NA)
}
}
#' Collapse domain ratings
#' @keywords internal
collapseDomainRatings = function(x, var){
prio = c("high risk" = 3, "some concerns" = 2, "low risk" = 1)
x[[var]] -> r.rating
suppressWarnings(names(
which(prio==max(prio[unique(r.rating)], na.rm = T)))) -> r.new
ifelse(length(r.new)>0, r.new, NA)
}
#' Domain 1 RoB Algorithm
#' @keywords internal
domain1Algorithm = function(d1_1, d1_2, d1_3, d1_4) {
if (identical(d1_2, "No/PN")) {"high risk"}
else if (identical(d1_2, "NI") & (identical(d1_3, "No/PN")|identical(d1_4, "No/PN"))) {"high risk"}
else if (identical(d1_2, "NI") & ((identical(d1_3, "Yes/PY")|identical(d1_3, "NI"))&(identical(d1_4, "Yes/PY")|identical(d1_4, "NI")))) {"some concerns"}
else if (identical(d1_2, "Yes/PY") & identical(d1_1, "No/PN")) {"some concerns"}
else if (identical(d1_2, "Yes/PY") & (identical(d1_1, "Yes/PY")|identical(d1_1, "NI")) & (identical(d1_3, "No/PN")|identical(d1_4, "No/PN"))) {"some concerns"}
else if (identical(d1_2, "Yes/PY") & (identical(d1_1, "Yes/PY")|identical(d1_1, "NI")) & ((identical(d1_3, "Yes/PY")|identical(d1_3, "NI"))&(identical(d1_4, "Yes/PY")|identical(d1_4, "NI")))) {"low risk"}
else NA
}
#' Domain 2 RoB Algorithm
#' @keywords internal
domain2Algorithm = function(d2_5, d2_6, d2_7, d2_8, d2_9) {
if (identical(d2_5, "Yes/PY") & identical(d2_6, "Yes/PY")) {"low risk"}
else if ((identical(d2_7, "NI")|identical(d2_7, "Yes/PY")) & identical(d2_8, "Yes/PY")) {"low risk"}
else if ((identical(d2_7, "NI")|identical(d2_7, "Yes/PY")) & (identical(d2_8, "No/PN")|identical(d2_8, "NI")) & (identical(d2_9, "Yes/PY"))) {"some concerns"}
else if ((identical(d2_7, "NI")|identical(d2_7, "Yes/PY")) & (identical(d2_8, "No/PN")|identical(d2_8, "NI")) & (identical(d2_9, "No/PN")|identical(d2_9, "NI"))) {"high risk"}
else if (identical(d2_7, "No/PN")) {"high risk"}
else NA
}
#' Domain 3 RoB Algorithm
#' @keywords internal
domain3Algorithm = function(d3_10, d3_11, d3_12, d3_13, d3_14) {
if (identical(d3_10, "Yes/PY")) {"low risk"}
else if ((identical(d3_10, "No/PN")|identical(d3_10, "NI")) & identical(d3_11, "Yes/PY")) {"low risk"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & identical(d3_12, "Yes/PY") & identical(d3_13, "Yes/PY") & identical(d3_14, "Yes/PY")) {"some concerns"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & identical(d3_12, "Yes/PY") & (identical(d3_13, "No/PN")|identical(d3_13, "NI")) & identical(d3_14, "Yes/PY")) {"some concerns"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & identical(d3_12, "Yes/PY") & identical(d3_13, "Yes/PY") & (identical(d3_14, "No/PN")|identical(d3_14, "NI"))) {"some concerns"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & identical(d3_12, "Yes/PY") & (identical(d3_13, "No/PN")|identical(d3_13, "NI")) & (identical(d3_14, "No/PN")|identical(d3_14, "NI"))) {"high risk"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & (identical(d3_12, "No/PN")|identical(d3_12, "NI")) & identical(d3_13, "Yes/PY") & identical(d3_14, "Yes/PY")) {"some concerns"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & (identical(d3_12, "No/PN")|identical(d3_12, "NI")) & (identical(d3_13, "No/PN")|identical(d3_13, "NI")) & identical(d3_14, "Yes/PY")) {"high risk"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & (identical(d3_12, "No/PN")|identical(d3_12, "NI")) & identical(d3_13, "Yes/PY") & (identical(d3_14, "No/PN")|identical(d3_14, "NI"))) {"high risk"}
else if ((identical(d3_11, "No/PN")|identical(d3_11, "NI")) & (identical(d3_12, "No/PN")|identical(d3_12, "NI")) & (identical(d3_13, "No/PN")|identical(d3_13, "NI")) & (identical(d3_14, "No/PN")|identical(d3_14, "NI"))) {"high risk"}
else NA
}
#' Domain 4 RoB Algorithm
#' @keywords internal
domain4Algorithm = function(d4_15, d4_16, d4_17, d4_18) {
if (identical(d4_16, "Yes/PY") & identical(d4_17, "No/PN")) {"low risk"}
else if (identical(d4_16, "No/PN") & identical(d4_17, "Yes/PY") & identical(d4_18, "Yes/PY")) {"low risk"}
else if (identical(d4_16, "No/PN") & identical(d4_17, "Yes/PY") & (identical(d4_18, "No/PN")|identical(d4_18, "NI"))) {"high risk"}
else if (identical(d4_16, "Yes/PY") & identical(d4_17, "Yes/PY") & identical(d4_18, "Yes/PY")) {"low risk"}
else if (identical(d4_16, "Yes/PY") & identical(d4_17, "Yes/PY") & (identical(d4_18, "No/PN")|identical(d4_18, "NI"))) {"high risk"}
else NA
}
#' Domain 5 RoB Algorithm
#' @keywords internal
domain5Algorithm = function(d5_19, d5_20, d5_21, d5_22, d5_23, d5_24) {
if ((identical(d5_19, "NI")|identical(d5_19, "No/PN"))) {"some concerns"}
else if ((identical(d5_21, "NI")|identical(d5_21, "No/PN"))) {"some concerns"}
else if (identical(d5_22, "Yes/PY") & identical(d5_24, "No/PN")) {"high risk"}
else if (identical(d5_22, "Yes/PY")) {"low risk"}
else if (identical(d5_22, "NI") & identical(d5_24, "No/PN")) {"high risk"}
else if (identical(d5_22, "NI")) {"some concerns"}
else if (identical(d5_22, "No/PN")) {"high risk"}
else NA
}
#' Overall RoB Algorithm
#' @keywords internal
overallAlgorithm = function(d1, d2, d3, d4, d5) {
ratings = c(d1, d2, d3, d4, d5)
if (sum(is.na(ratings))>0) { NA } else {
lows = sum(ratings=="low risk"); highs = sum(ratings=="high risk")
concerns = sum(ratings=="some concerns")
if (lows==5) {"low risk"}
else if (highs > 0 | concerns > 2) {"high risk"}
else if (concerns > 0 | concerns <= 2) {"some concerns"}
else NA
}
}
#' Tests if value is `NA` or `NaN`
#'
#' @param x Value to test.
#' @usage isNAorNaN(x)
#' @export
#' @keywords internal
isNAorNaN = function(x){
is.na(x) | is.nan(x)
}
#' Extract Hedges _g_ values
#'
#' @param x `data.frame` with effect size results.
#' @usage extractG(x)
#' @export
#' @keywords internal
extractG = function(x){
mask = apply(
x, 1, function(f) !isNAorNaN(f), simplify = FALSE) %>%
do.call(rbind, .)
index = apply(mask, 1, which, simplify = FALSE)
lapply(as.list(1:length(index)),
function(i) {
y = x[i, index[[i]]]
if (length(y) <= 1) {
return(data.frame(es = NA, se = NA)[,c("es", "se")]) }
else {return(y[,c("es", "se")])}}) %>%
do.call(rbind, .) -> x.select
return(x.select)
}
#' Pipe operator
#'
#' See \code{magrittr::\link[magrittr:pipe]{\%>\%}} for details.
#'
#' @name %>%
#' @rdname pipe
#' @keywords internal
#' @export
#' @importFrom tidyr %>%
#' @usage lhs \%>\% rhs
#' @param lhs A value or the magrittr placeholder.
#' @param rhs A function call using the magrittr semantics.
#' @return The result of calling `rhs(lhs)`.
NULL
#' Select available arguments in function
#' @keywords internal
selectArguments = function(f, dots){
func.args = names(as.list(args(f)))
return(dots[names(dots) %in% func.args])
}
#' Try function and catch errors
#' @keywords internal
tryCatch2 = function(expr) {
warn = err = NULL
value = withCallingHandlers(
tryCatch(expr, error=function(e) {
err <<- e
NULL
}), warning=function(w) {
warn <<- w
invokeRestart("muffleWarning")
})
list(value=value, warning=warn,
error=err, has.error = is.null(value))
}
# get.critical helper function for flagging studies
#' @keywords internal
get.critical = function(x, p = 0.95, ...) {
qfun = match.fun(paste0("q", x$distname))
do.call(qfun, c(list(p = p, ...), as.list(x$estimate)))
}
# Helper function to plot density and histogram
#' @keywords internal
#' @importFrom graphics hist
#' @importFrom grDevices rgb
plotDensityHist = function(x, breaks = "FD", xlab = "Effect Size",
main = NULL, col_hist = rgb(0.2, 0.4, 0.8, 0.35),
border = "grey30", col_line = "firebrick", lwd = 2,
rug = TRUE, xlim = NULL) {
lookup = x$lookup
x = with(x, data.frame(smd = smd, se = se, flag.effect = flag.effect,
flag.power = flag.power, flag.rob = flag.rob, flags = flags))
x = x[is.finite(x$smd), ]
if (!length(x$smd)) stop("'x' has no finite values.")
if (is.null(xlim)) xlim = range(x$smd, -.01, 3, na.rm = TRUE)
h = suppressWarnings(hist(x$smd, breaks = breaks, probability = TRUE, xlim = xlim, plot = FALSE))
xs = seq(xlim[1], xlim[2], length.out = 512)
# Reference density values
dfun = match.fun(paste0("d", lookup$distname[1]))
args = c(as.list(lookup[1, , drop = TRUE]), list(x = xs)) # use first row of lookup
args = args[intersect(names(args), names(formals(dfun)))] # keep only recognized args
ys = do.call(dfun, args)
# Pick ylim from the larger of hist density vs. curve
y_max = max(h$density, ys, na.rm = TRUE)
ylim = c(0, y_max * 1.05) # small headroom
# Now plot histogram using the computed ylim
hist(x$smd, breaks = breaks, probability = TRUE, col = col_hist, border = border,
xlab = xlab, xlim = xlim, ylim = ylim,
main = if (is.null(main)) {
paste0("Reference distribution (", lookup$distname[1],
") and\nempirical effect sizes")
} else main)
# Overlay the density
lines(xs, ys, col = col_line, lwd = lwd)
if (rug) rug(x$smd, col = border)
invisible(list(hist = h, curve_x = xs,
curve_y = ys, ylim = ylim))
}
#' Send message after fitting model
#' @keywords internal
sendMessage = function(obj, model.name = NULL,
which.run = NULL, .type.es = NULL,
es.type = NULL){
if (identical(obj, "start")){
message(crayon::cyan(crayon::bold("- Running meta-analyses...")))
msg.es = if (identical(.type.es, "RR")) {
ifelse(identical(es.type[1], "precalculated"),
crayon::bold(crayon::magenta("risk ratio (pre-calculated)")),
crayon::bold(crayon::magenta("risk ratio (raw event data)")))
} else if (identical(.type.es, "ROM")) {
crayon::bold(crayon::magenta("Ratio-of-Means"))
} else {
crayon::bold(crayon::magenta("Hedges' g"))
}
message("- ", crayon::green("[OK] "), "Using ", msg.es, " as effect size metric... ")
} else {
if (model.name %in% which.run){
if (!obj$has.error) {
message(crayon::green("DONE"))
} else {
message(crayon::yellow("ERROR"))
message("- ", crayon::yellow("[!] "), "'", model.name, "' ",
"model could not be calculated. Error: ",
obj$message)
}
}
}}
#' Fit 'overall' model
#' @keywords internal
fitOverallModel = function(data, es.var, se.var, arm.var.1, arm.var.2,
measure.var, study.var, .raw.bin.es, .type.es, hakn,
method.tau.meta, method.tau.ci, method.tau,
dots, es.binary.raw.vars, round.digits,
nntCer, which.run, rob.data){
data.original = data
round.digits = abs(round.digits)
# Guard against malformed call objects passed via rerun():
# coerce which.run to a plain character vector for %in% checks.
if (is.function(which.run)) {
which.run = character(0)
} else if (is.language(which.run) || is.call(which.run)) {
which.run = tryCatch(eval(which.run), error = function(e) character(0))
}
which.run = as.character(unlist(which.run, use.names = FALSE))
# Create comparison variable
paste0(data[[study.var]], " (",
data[[arm.var.1]], " vs. ",
data[[arm.var.2]], "; ",
data[[measure.var]], ")") -> data$comparison
paste0(data[[arm.var.1]], " vs. ",
data[[arm.var.2]]) -> data$comparison.only
data[[measure.var]] -> data$instrument