/
nma.R
3366 lines (2910 loc) · 143 KB
/
nma.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
#' Network meta-analysis models
#'
#' The `nma` function fits network meta-analysis and (multilevel) network
#' meta-regression models in Stan.
#'
#' @param network An `nma_data` object, as created by the functions `set_*()`,
#' `combine_network()`, or `add_integration()`
#' @param consistency Character string specifying the type of (in)consistency
#' model to fit, either `"consistency"`, `"ume"`, or `"nodesplit"`
#' @param trt_effects Character string specifying either `"fixed"` or `"random"` effects
#' @param regression A one-sided model formula, specifying the prognostic and
#' effect-modifying terms for a regression model. Any references to treatment
#' should use the `.trt` special variable, for example specifying effect
#' modifier interactions as `variable:.trt` (see details).
#' @param class_interactions Character string specifying whether effect modifier
#' interactions are specified as `"common"`, `"exchangeable"`, or
#' `"independent"`.
#' @param likelihood Character string specifying a likelihood, if unspecified
#' will be inferred from the data (see details)
#' @param link Character string specifying a link function, if unspecified will
#' default to the canonical link (see details)
#' @param ... Further arguments passed to
#' \code{\link[rstan:stanmodel-method-sampling]{sampling()}}, such as `iter`,
#' `chains`, `cores`, etc.
#' @param nodesplit For `consistency = "nodesplit"`, the comparison(s) to split
#' in the node-splitting model(s). Either a length 2 vector giving the
#' treatments in a single comparison, or a 2 column data frame listing
#' multiple treatment comparisons to split in turn. By default, all possible
#' comparisons will be chosen (see [get_nodesplits()]).
#' @param prior_intercept Specification of prior distribution for the intercept
#' @param prior_trt Specification of prior distribution for the treatment effects
#' @param prior_het Specification of prior distribution for the heterogeneity
#' (if `trt_effects = "random"`)
#' @param prior_het_type Character string specifying whether the prior
#' distribution `prior_het` is placed on the heterogeneity standard deviation
#' \eqn{\tau} (`"sd"`, the default), variance \eqn{\tau^2} (`"var"`), or
#' precision \eqn{1/\tau^2} (`"prec"`).
#' @param prior_reg Specification of prior distribution for the regression
#' coefficients (if `regression` formula specified)
#' @param prior_aux Specification of prior distribution for the auxiliary
#' parameter, if applicable (see details). For `likelihood = "gengamma"` this
#' should be a list of prior distributions with elements `sigma` and `k`.
#' @param prior_aux_reg Specification of prior distribution for the auxiliary
#' regression parameters, if `aux_regression` is specified (see details).
#' @param aux_by Vector of variable names listing the variables to stratify the
#' auxiliary parameters by. Currently only used for survival models, see
#' details. Cannot be used with `aux_regression`.
#' @param aux_regression A one-sided model formula giving a regression model for
#' the auxiliary parameters. Currently only used for survival models, see
#' details. Cannot be used with `aux_by`.
#' @param QR Logical scalar (default `FALSE`), whether to apply a QR
#' decomposition to the model design matrix
#' @param center Logical scalar (default `TRUE`), whether to center the
#' (numeric) regression terms about the overall means
#' @param adapt_delta See [adapt_delta] for details
#' @param int_thin A single integer value, the thinning factor for returning
#' cumulative estimates of integration error. Saving cumulative estimates is
#' disabled by `int_thin = 0`, which is the default.
#' @param int_check Logical, check sufficient accuracy of numerical integration
#' by fitting half of the chains with `n_int/2`? When `TRUE`, `Rhat` and
#' `n_eff` diagnostic warnings will be given if numerical integration has not
#' sufficiently converged (suggesting increasing `n_int` in
#' [add_integration()]). Default `TRUE`, but disabled (`FALSE`) when
#' `int_thin > 0`.
#' @param mspline_degree Non-negative integer giving the degree of the M-spline
#' polynomial for `likelihood = "mspline"`. Piecewise exponential hazards
#' (`likelihood = "pexp"`) are a special case with `mspline_degree = 0`.
#' @param n_knots For `mspline` and `pexp` likelihoods, a non-negative integer
#' giving the number of internal knots for partitioning the baseline hazard
#' into intervals. The knot locations within each study will be determined by
#' the corresponding quantiles of the observed event times, plus boundary
#' knots at the earliest entry time (0 with no delayed entry) and the maximum
#' event/censoring time. For example, with `n_knots = 3`, the internal knot
#' locations will be at the 25%, 50%, and 75% quantiles of the observed event
#' times. The default is `n_knots = 7`; overfitting is avoided by shrinking
#' towards a constant hazard with a random walk prior (see details). If
#' `aux_regression` is specified then a single set of knot locations will be
#' calculated across all studies in the network. See [make_knots()] for more
#' details on the knot positioning algorithms. Ignored when `knots` is
#' specified.
#' @param knots For `mspline` and `pexp` likelihoods, a named list of numeric
#' vectors of knot locations (including boundary knots) for each of the
#' studies in the network. Currently, each vector must have the same length
#' (i.e. each study must use the same number of knots). Alternatively, a
#' single numeric vector of knot locations can be provided which will be
#' shared across all studies in the network. If unspecified (the default), the
#' knots will be chosen based on `n_knots` as described above. If
#' `aux_regression` is specified then `knots` should be a single numeric
#' vector of knot locations which will be shared across all studies in the
#' network. [make_knots()] can be used to help specify `knots` directly, or to
#' investigate knot placement prior to model fitting.
#' @param mspline_basis Instead of specifying `mspline_degree` and `n_knots` or
#' `knots`, a named list of M-spline bases (one for each study) can be
#' provided with `mspline_basis` which will be used directly. In this case,
#' all other M-spline options will be ignored.
#'
#' @details When specifying a model formula in the `regression` argument, the
#' usual formula syntax is available (as interpreted by [model.matrix()]). The
#' only additional requirement here is that the special variable `.trt` should
#' be used to refer to treatment. For example, effect modifier interactions
#' should be specified as `variable:.trt`. Prognostic (main) effects and
#' interactions can be included together compactly as `variable*.trt`, which
#' expands to `variable + variable:.trt` (plus `.trt`, which is already in the
#' NMA model).
#'
#' For the advanced user, the additional specials `.study` and `.trtclass` are
#' also available, and refer to studies and (if specified) treatment classes
#' respectively. When node-splitting models are fitted (`consistency =
#' "nodesplit"`) the special `.omega` is available, indicating the arms
#' to which the node-splitting inconsistency factor is added.
#'
#' See \code{\link[multinma:priors]{?priors}} for details on prior
#' specification. Default prior distributions are available, but may not be
#' appropriate for the particular setting and will raise a warning if used. No
#' attempt is made to tailor these defaults to the data provided. Please
#' consider appropriate prior distributions for the particular setting,
#' accounting for the scales of outcomes and covariates, etc. The function
#' [plot_prior_posterior()] may be useful in examining the influence of the
#' chosen prior distributions on the posterior distributions, and the
#' \code{\link[multinma:summary.nma_prior]{summary()}} method for `nma_prior`
#' objects prints prior intervals.
#'
#' @section Likelihoods and link functions:
#' Currently, the following likelihoods and link functions are supported for
#' each data type:
#'
#' | \strong{Data type} | \strong{Likelihood} | \strong{Link function} |
#' |--------------------|-----------------------|------------------------|
#' | \strong{Binary} | `bernoulli`, `bernoulli2`| `logit`, `probit`, `cloglog`
#' | \strong{Count} | `binomial`, `binomial2` | `logit`, `probit`, `cloglog`
#' | \strong{Rate} | `poisson` | `log`
#' | \strong{Continuous}| `normal` | `identity`, `log`
#' | \strong{Ordered} | `ordered` | `logit`, `probit`, `cloglog`
#' | \strong{Survival} | `exponential`, `weibull`, `gompertz`, `exponential-aft`, `weibull-aft`, `lognormal`, `loglogistic`, `gamma`, `gengamma`, `mspline`, `pexp` | `log`
#'
#' The `bernoulli2` and `binomial2` likelihoods correspond to a two-parameter
#' Binomial likelihood for arm-based AgD, which more closely matches the
#' underlying Poisson Binomial distribution for the summarised aggregate
#' outcomes in a ML-NMR model than the typical (one parameter) Binomial
#' distribution \insertCite{@see @methods_paper}{multinma}.
#'
#' When a `cloglog` link is used, including an offset for log follow-up time
#' (i.e. `regression = ~offset(log(time))`) results in a model on the log
#' hazard \insertCite{@see @TSD2}{multinma}.
#'
#' For survival data, all accelerated failure time models (`exponential-aft`,
#' `weibull-aft`, `lognormal`, `loglogistic`, `gamma`, `gengamma`) are
#' parameterised so that the treatment effects and any regression parameters
#' are log Survival Time Ratios (i.e. a coefficient of \eqn{\log(2)} means
#' that the treatment or covariate is associated with a doubling of expected
#' survival time). These can be converted to log Acceleration Factors using
#' the relation \eqn{\log(\mathrm{AF}) = -\log(\mathrm{STR})} (or equivalently
#' \eqn{\mathrm{AF} = 1/\mathrm{STR}}).
#'
#' Further details on each likelihood and link function are given by
#' \insertCite{TSD2;textual}{multinma}.
#'
#'
#' @section Auxiliary parameters:
#' Auxiliary parameters are only present in the following models.
#'
#' ## Normal likelihood with IPD
#' When a Normal likelihood is fitted to IPD, the auxiliary parameters are the
#' arm-level standard deviations \eqn{\sigma_{jk}} on treatment \eqn{k} in
#' study \eqn{j}.
#'
#' ## Ordered multinomial likelihood
#' When fitting a model to \eqn{M} ordered outcomes, the auxiliary parameters
#' are the latent cutoffs between each category, \eqn{c_0 < c_1 < \dots <
#' c_M}. Only \eqn{c_2} to \eqn{c_{M-1}} are estimated; we fix \eqn{c_0 =
#' -\infty}, \eqn{c_1 = 0}, and \eqn{c_M = \infty}. When specifying priors for
#' these latent cutoffs, we choose to specify priors on the *differences*
#' \eqn{c_{m+1} - c_m}. Stan automatically truncates any priors so that the
#' ordering constraints are satisfied.
#'
#' ## Survival (time-to-event) likelihoods
#' All survival likelihoods except the `exponential` and `exponential-aft`
#' likelihoods have auxiliary parameters. These are typically study-specific
#' shape parameters \eqn{\gamma_j>0}, except for the `lognormal` likelihood
#' where the auxiliary parameters are study-specific standard deviations on
#' the log scale \eqn{\sigma_j>0}.
#'
#' The `gengamma` likelihood has two sets of auxiliary parameters,
#' study-specific scale parameters \eqn{\sigma_j>0} and shape parameters
#' \eqn{k_j}, following the parameterisation of
#' \insertCite{Lawless1980;textual}{multinma}, which permits a range of
#' behaviours for the baseline hazard including increasing, decreasing,
#' bathtub and arc-shaped hazards. This parameterisation is related to that
#' discussed by \insertCite{Cox2007;textual}{multinma} and implemented in the
#' `flexsurv` package with \eqn{Q = k^{-0.5}}. The parameterisation used here
#' effectively bounds the shape parameter \eqn{k} away from numerical
#' instabilities as \eqn{k \rightarrow \infty} (i.e. away from \eqn{Q
#' \rightarrow 0}, the log-Normal distribution) via the prior distribution.
#' Implicitly, this parameterisation is restricted to \eqn{Q > 0} and so
#' certain survival distributions like the inverse-Gamma and inverse-Weibull
#' are not part of the parameter space; however, \eqn{Q > 0} still encompasses
#' the other survival distributions implemented in this package.
#'
#' For the `mspline` and `pexp` likelihoods, the auxiliary parameters are the
#' spline coefficients for each study. These form a unit simplex (i.e. lie
#' between 0 and 1, and sum to 1), and are given a random walk prior
#' distribution. `prior_aux` specifies the hyperprior on the random walk
#' standard deviation \eqn{\sigma} which controls the level of smoothing of
#' the baseline hazard, with \eqn{\sigma = 0} corresponding to a constant
#' baseline hazard.
#'
#' The auxiliary parameters can be stratified by additional factors through
#' the `aux_by` argument. For example, to allow the shape of the baseline
#' hazard to vary between treatment arms as well as studies, use `aux_by =
#' c(".study", ".trt")`. (Technically, `.study` is always included in the
#' stratification even if omitted from `aux_by`, but we choose here to make
#' the stratification explicit.) This is a common way of relaxing the
#' proportional hazards assumption. The default is equivalent to `aux_by =
#' ".study"` which stratifies the auxiliary parameters by study, as described
#' above.
#'
#' A regression model may be specified on the auxiliary parameters using
#' `aux_regression`. This is useful if we wish to model departures from
#' non-proportionality, rather than allowing the baseline hazards to be
#' completely independent using `aux_by`. This is necessary if absolute
#' predictions (e.g. survival curves) are required in a population for
#' unobserved combinations of covariates; for example, if `aux_by = .trt` then
#' absolute predictions may only be produced for the observed treatment arms
#' in each study population, whereas if `aux_regression = ~.trt` then absolute
#' predictions can be produced for all treatments in any population. For
#' `mspline` and `pexp` likelihoods, the regression coefficients are smoothed
#' over time using a random walk prior to avoid overfitting: `prior_aux_reg`
#' specifies the hyperprior for the random walk standard deviation. For other
#' parametric likelihoods, `prior_aux_reg` specifies the prior for the
#' auxiliary regression coefficients.
#'
#' @return `nma()` returns a [stan_nma] object, except when `consistency =
#' "nodesplit"` when a [nma_nodesplit] or [nma_nodesplit_df] object is
#' returned. `nma.fit()` returns a [stanfit] object.
#' @export
#'
#' @references
#' \insertAllCited{}
#'
#' @examples
#' ## Smoking cessation NMA
#' @template ex_smoking_network
#' @template ex_smoking_nma_fe
#' @template ex_smoking_nma_re
#' @template ex_smoking_nma_re_ume
#' @template ex_smoking_nma_re_nodesplit
#' @examples \donttest{
#' # Summarise the node-splitting results
#' summary(smk_fit_RE_nodesplit)
#' }
#'
#' ## Plaque psoriasis ML-NMR
#' @template ex_plaque_psoriasis_network
#' @template ex_plaque_psoriasis_integration
#' @template ex_plaque_psoriasis_mlnmr
#'
#' @examples
#' ## Newly-diagnosed multiple myeloma NMA
#' @template ex_ndmm_network
#' @template ex_ndmm
nma <- function(network,
consistency = c("consistency", "ume", "nodesplit"),
trt_effects = c("fixed", "random"),
regression = NULL,
class_interactions = c("common", "exchangeable", "independent"),
likelihood = NULL,
link = NULL,
...,
nodesplit = get_nodesplits(network, include_consistency = TRUE),
prior_intercept = .default(normal(scale = 100)),
prior_trt = .default(normal(scale = 10)),
prior_het = .default(half_normal(scale = 5)),
prior_het_type = c("sd", "var", "prec"),
prior_reg = .default(normal(scale = 10)),
prior_aux = .default(),
prior_aux_reg = .default(),
aux_by = NULL,
aux_regression = NULL,
QR = FALSE,
center = TRUE,
adapt_delta = NULL,
int_thin = 0,
int_check = TRUE,
mspline_degree = 3,
n_knots = 7,
knots = NULL,
mspline_basis = NULL) {
# Check network
if (!inherits(network, "nma_data")) {
abort("Expecting an `nma_data` object, as created by the functions `set_*`, `combine_network`, or `add_integration`.")
}
if (all(purrr::map_lgl(network, is.null))) {
abort("Empty network.")
}
# Check model arguments
consistency <- rlang::arg_match(consistency)
if (length(consistency) > 1) abort("`consistency` must be a single string.")
trt_effects <- rlang::arg_match(trt_effects)
if (length(trt_effects) > 1) abort("`trt_effects` must be a single string.")
if (consistency == "nodesplit") {
lvls_trt <- levels(network$treatments)
nodesplit_include_consistency <- FALSE
if (is.data.frame(nodesplit)) { # Data frame listing comparisons to split
if (ncol(nodesplit) != 2)
abort("The data frame passed to `nodesplit` should have two columns.")
nodesplit <- tibble::as_tibble(nodesplit)
colnames(nodesplit) <- c("trt1", "trt2")
# NA rows indicate include_consistency = TRUE, filter these out
if (any(is.na(nodesplit[,1]) & is.na(nodesplit[,2]))) {
nodesplit_include_consistency <- TRUE
nodesplit <- dplyr::filter(nodesplit, !is.na(.data$trt1) & !is.na(.data$trt2))
}
if (nrow(nodesplit) == 0) {
abort("No comparisons to node-split.")
}
nodesplit$trt1 <- as.character(nodesplit$trt1)
nodesplit$trt2 <- as.character(nodesplit$trt2)
if (!all(unlist(nodesplit) %in% lvls_trt))
abort(sprintf("All comparisons in `nodesplit` should match two treatments in the network.\nSuitable values are: %s",
ifelse(length(lvls_trt) <= 5,
paste0(lvls_trt, collapse = ", "),
paste0(paste0(lvls_trt[1:5], collapse = ", "), ", ..."))))
if (any(nodesplit[,1] == nodesplit[,2]))
abort("`nodesplit` comparison cannot be the same treatment against itself.")
# Check valid nodesplit - must have both direct and indirect evidence
ns_check <- dplyr::rowwise(nodesplit) %>%
dplyr::mutate(direct = has_direct(network, .data$trt1, .data$trt2),
indirect = has_indirect(network, .data$trt1, .data$trt2),
valid = .data$direct && .data$indirect)
if (any(!ns_check$valid)) {
ns_valid <- dplyr::filter(ns_check, .data$valid) %>%
dplyr::ungroup() %>%
dplyr::select("trt1", "trt2")
ns_invalid <- dplyr::filter(ns_check, !.data$valid) %>%
dplyr::mutate(comparison = paste(.data$trt1, .data$trt2, sep = " vs. "))
if (nrow(ns_valid)) {
warn(glue::glue(
"Ignoring node-split comparisons without both both direct and independent indirect evidence: ",
glue::glue_collapse(ns_invalid$comparison, sep = ", ", width = 100), "."
))
nodesplit <- ns_valid
} else {
abort("No valid comparisons for node-splitting given in `nodesplit`.\n Comparisons must have both direct and independent indirect evidence for node-splitting.")
}
}
# Store comparisons as factors, in increasing order (i.e. trt1 < trt2)
nodesplit$trt1 <- factor(nodesplit$trt1, levels = lvls_trt)
nodesplit$trt2 <- factor(nodesplit$trt2, levels = lvls_trt)
for (i in 1:nrow(nodesplit)) {
if (as.numeric(nodesplit$trt1[i]) > as.numeric(nodesplit$trt2[i])) {
nodesplit[i, ] <- rev(nodesplit[i, ])
}
}
# Iteratively call node-splitting models
n_ns <- nrow(nodesplit) + nodesplit_include_consistency
ns_fits <- vector("list", n_ns)
ns_arglist <- list(network = network,
consistency = "nodesplit",
trt_effects = trt_effects,
regression = regression,
likelihood = likelihood,
link = link,
...,
prior_intercept = prior_intercept,
prior_trt = prior_trt,
prior_het = prior_het,
prior_het_type = prior_het_type,
prior_reg = prior_reg,
prior_aux = prior_aux,
prior_aux_reg = prior_aux_reg,
aux_by = aux_by,
aux_regression = aux_regression,
QR = QR,
center = center,
adapt_delta = adapt_delta,
int_thin = int_thin,
mspline_degree = mspline_degree,
n_knots = n_knots,
knots = knots,
mspline_basis = mspline_basis)
if (!missing(class_interactions)) ns_arglist$class_interactions <- class_interactions
for (i in 1:nrow(nodesplit)) {
inform(glue::glue("Fitting model {i} of {n_ns}, node-split: ",
as.character(nodesplit$trt2[i]),
" vs. ",
as.character(nodesplit$trt1[i])))
ns_arglist$nodesplit <- forcats::fct_c(nodesplit$trt1[i], nodesplit$trt2[i])
ns_fits[[i + nodesplit_include_consistency]] <- do.call(nma, ns_arglist)
}
if (nodesplit_include_consistency) {
inform(glue::glue("Fitting model {n_ns} of {n_ns}, consistency model"))
nodesplit <- tibble::add_row(nodesplit, .before = 1)
ns_arglist$consistency <- "consistency"
ns_arglist$nodesplit <- NULL
ns_fits[[1]] <- do.call(nma, ns_arglist)
}
nodesplit$model <- ns_fits
# Return a nma_nodesplit_df object
class(nodesplit) <- c("nma_nodesplit_df", class(nodesplit))
return(nodesplit)
} else if (rlang::is_vector(nodesplit, n = 2)) { # Vector giving single comparison to split
nodesplit <- as.character(nodesplit)
if (!all(nodesplit %in% lvls_trt))
abort(sprintf("The `nodesplit` treatment comparison should match two treatments in the network.\nSuitable values are: %s",
ifelse(length(lvls_trt) <= 5,
paste0(lvls_trt, collapse = ", "),
paste0(paste0(lvls_trt[1:5], collapse = ", "), ", ..."))))
if (nodesplit[1] == nodesplit[2])
abort("`nodesplit` comparison cannot be the same treatment against itself.")
# Check valid nodesplit - must have both direct and indirect evidence
if (!has_direct(network, nodesplit[1], nodesplit[2])) {
abort(glue::glue("Cannot node-split the {nodesplit[1]} vs. {nodesplit[2]} comparison, no direct evidence."))
}
if (!has_indirect(network, nodesplit[1], nodesplit[2])) {
abort(glue::glue("Cannot node-split the {nodesplit[1]} vs. {nodesplit[2]} comparison, no independent indirect evidence."))
}
# Store comparison as factor, in increasing order (i.e. trt1 < trt2)
nodesplit <- factor(nodesplit, levels = lvls_trt)
if (as.numeric(nodesplit[1]) > as.numeric(nodesplit[2])) {
nodesplit <- rev(nodesplit)
}
} else {
abort("`nodesplit` should either be a length 2 vector or a 2 column data frame, giving the comparison(s) to node-split.")
}
}
if (!is.null(regression) && !rlang::is_formula(regression, lhs = FALSE)) {
abort("`regression` should be a one-sided formula.")
}
if (is.null(network$classes)) {
if (!missing(class_interactions)) {
abort(paste("Setting `class_interactions` requires treatment classes to be specified in the network.",
"See set_*() argument `trt_class`.", sep = "\n"))
} else if (!is.null(regression)) {
inform(paste("Note: No treatment classes specified in network, any interactions in `regression` formula will be separate (independent) for each treatment.",
"Use set_*() argument `trt_class` and nma() argument `class_interactions` to change this.", sep = "\n"))
}
}
class_interactions <- rlang::arg_match(class_interactions)
if (length(class_interactions) > 1) abort("`class_interactions` must be a single string.")
likelihood <- check_likelihood(likelihood, network$outcome)
link <- check_link(link, likelihood)
# When are priors on auxiliary parameters required?
has_aux <- (likelihood == "normal" && has_ipd(network)) ||
likelihood %in% c("ordered", "weibull", "gompertz",
"weibull-aft", "lognormal", "loglogistic",
"gamma", "gengamma", "mspline", "pexp")
# Are study intercepts present? Not if only contrast data
has_intercepts <- has_agd_arm(network) || has_ipd(network)
# Check priors
check_prior(prior_intercept)
check_prior(prior_trt)
check_prior(prior_het)
check_prior(prior_reg)
if (!.is_default(prior_aux)) {
if (likelihood == "gengamma") check_prior(prior_aux, c("sigma", "k"))
else check_prior(prior_aux)
}
prior_het_type <- rlang::arg_match(prior_het_type)
# Prior defaults
prior_defaults <- list()
if (has_intercepts && .is_default(prior_intercept))
prior_defaults$prior_intercept <- get_prior_call(prior_intercept)
if (.is_default(prior_trt))
prior_defaults$prior_trt <- get_prior_call(prior_trt)
if (trt_effects == "random" && .is_default(prior_het))
prior_defaults$prior_het <- get_prior_call(prior_het)
if (!is.null(regression) && !is_only_offset(regression) && .is_default(prior_reg))
prior_defaults$prior_reg <- get_prior_call(prior_reg)
if (has_aux && .is_default(prior_aux)) {
if (likelihood == "normal" && has_ipd(network)) {
prior_aux <- .default(half_normal(scale = 5))
} else if (likelihood == "ordered") {
prior_aux <- .default(flat())
} else if (likelihood %in% c("weibull", "gompertz", "weibull-aft",
"lognormal", "loglogistic", "gamma")) {
prior_aux <- .default(half_normal(scale = 10))
} else if (likelihood == "gengamma") {
prior_aux <- .default(list(sigma = half_normal(scale = 10),
k = half_normal(scale = 10)))
} else if (likelihood %in% c("mspline", "pexp")) {
prior_aux <- .default(half_normal(scale = 1))
}
prior_defaults$prior_aux <- get_prior_call(prior_aux)
}
if (has_aux && !is.null(aux_regression) && .is_default(prior_aux_reg)) {
if (likelihood %in% c("mspline", "pexp")) {
prior_aux_reg <- .default(half_normal(scale = 1))
} else if (likelihood %in% valid_lhood$survival) {
prior_aux_reg <- .default(normal(scale = 10))
}
prior_defaults$prior_aux_reg <- get_prior_call(prior_aux_reg)
}
# Warn where default priors are used
if (!rlang::is_empty(prior_defaults)) {
warn(glue::glue(
"Prior distributions were left at default values:",
paste(paste(names(prior_defaults), prior_defaults, sep = " = "), collapse = "\n"),
.sep = "\n"
))
}
# Check other args
if (!rlang::is_bool(QR)) abort("`QR` should be a logical scalar (TRUE or FALSE).")
if (!rlang::is_bool(center)) abort("`center` should be a logical scalar (TRUE or FALSE).")
if (!rlang::is_scalar_integerish(int_thin) ||
int_thin < 0) abort("`int_thin` should be an integer >= 0.")
if (!rlang::is_bool(int_check)) abort("`int_check` should be a logical scalar (TRUE or FALSE).")
if (int_thin > 0) int_check <- FALSE
# Set adapt_delta
if (is.null(adapt_delta)) {
adapt_delta <- switch(trt_effects, fixed = 0.8, random = 0.95)
} else if (!rlang::is_scalar_double(adapt_delta) ||
adapt_delta <= 0 || adapt_delta >= 1) abort("`adapt_delta` should be a numeric value in (0, 1).")
# Check aux_by / aux_regression combination
aux_by <- rlang::enquo(aux_by)
if (!rlang::quo_is_null(aux_by) && !is.null(aux_regression)) {
abort("Cannot specify both `aux_by` and `aux_regression`.")
}
# Set up aux_regression
has_aux_regression <- FALSE
if (!is.null(aux_regression) && likelihood %in% valid_lhood$survival &&
has_aux &&
(has_ipd(network) || has_agd_arm(network))) {
if (!rlang::is_formula(aux_regression, lhs = FALSE)) abort("`aux_regression` should be a one-sided formula.")
if (!is.null(attr(aux_regression, "offset"))) abort("Offset terms not allowed in `aux_regression`.")
# Remove main effect of study if specified, and make sure treatment handled properly (first, no intercept for M-spline model with symmetric RW prior)
if (".trt" %in% colnames(attr(terms(aux_regression), "factor"))) {
aux_regression <- update.formula(aux_regression, ~. -.study -.trt +1)
if (likelihood %in% c("mspline", "pexp")) aux_regression <- update.formula(aux_regression, ~.trt + . -1)
else aux_regression <- update.formula(aux_regression, ~.trt + . +1)
} else {
aux_regression <- update.formula(aux_regression, ~. -.study +1)
}
has_aux_regression <- TRUE
}
# Set up aux_by
if (likelihood %in% valid_lhood$survival &&
has_aux &&
(has_ipd(network) || has_agd_arm(network))) {
has_aux_by <- TRUE
if (rlang::quo_is_null(aux_by)) aux_by <- ".study"
aux_dat <- dplyr::bind_rows(if (has_ipd(network)) dplyr::select(network$ipd, -".Surv") else NULL,
if (has_agd_arm(network)) {
if (inherits(network, "mlnmr_data")) {
.unnest_integration(network$agd_arm) %>% dplyr::select(-".Surv")
} else {
dplyr::select(network$agd_arm, -".Surv")
}
} else NULL)
# Check specs and translate into string column names
aux_by <- colnames(get_aux_by_data(aux_dat, by = aux_by))
} else {
has_aux_by <- FALSE
aux_by <- NULL
}
# Use numerical integration? TRUE if class mlnmr_data and regression is not NULL
# (Avoids unnecessary use of integration points if regression formula not specified)
use_int <- inherits(network, "mlnmr_data") && (!is.null(regression) || aux_needs_integration(aux_regression = aux_regression, aux_by = aux_by))
# Number of numerical integration points
# Set to 1 if no numerical integration, so that regression on summary data is possible
n_int <- if (use_int) network$n_int else 1
# Warn if combining AgD and IPD in a meta-regression without using integration
if (!is.null(regression) && !inherits(network, "mlnmr_data") && has_ipd(network) &&
(has_agd_arm(network) || has_agd_contrast(network))) {
warn(glue::glue("No integration points available, using naive plug-in model at aggregate level.\n",
"Use `add_integration()` to add integration points to the network."))
}
# Notify if default reference treatment is used
if (.is_default(network$treatments))
inform(glue::glue('Note: Setting "{levels(network$treatments)[1]}" as the network reference treatment.'))
# Notify if network is disconnected
if (!is_network_connected(network))
inform("Note: Network is disconnected. See ?is_network_connected for more details.")
# Get data for design matrices and outcomes
if (has_ipd(network)) {
dat_ipd <- network$ipd
# Only take necessary columns
dat_ipd <- get_model_data_columns(dat_ipd,
regression = regression,
aux_regression = aux_regression,
label = "IPD",
keep = if (has_aux_by) aux_by else NULL)
y_ipd <- get_outcome_variables(network$ipd, network$outcome$ipd)
} else {
dat_ipd <- tibble::tibble()
y_ipd <- NULL
}
if (has_agd_arm(network)) {
dat_agd_arm <- network$agd_arm
y_agd_arm <- get_outcome_variables(dat_agd_arm, network$outcome$agd_arm)
# Unnest survival data
if (network$outcome$agd_arm == "survival") {
y_agd_arm <- tidyr::unnest(y_agd_arm, cols = ".Surv")
}
# Set up integration variables if present
if (use_int) {
if (network$outcome$agd_arm == "survival") {
idat_agd_arm <- dat_agd_arm %>%
# Drop duplicated names in outer dataset from .data_orig before unnesting
dplyr::mutate(.data_orig = purrr::map(.data$.data_orig, ~ dplyr::select(., -dplyr::any_of(names(dat_agd_arm))))) %>%
# Unnest - should have n_int contiguous rows for each survival time
tidyr::unnest(cols = c(".Surv", ".data_orig")) %>%
.unnest_integration()
} else {
idat_agd_arm <- .unnest_integration(dat_agd_arm)
}
} else {
if (network$outcome$agd_arm == "survival") {
idat_agd_arm <- dat_agd_arm %>%
# Drop duplicated names in outer dataset from .data_orig before unnesting
dplyr::mutate(.data_orig = purrr::map(.data$.data_orig, ~ dplyr::select(., -dplyr::any_of(names(dat_agd_arm))))) %>%
# Unnest - should have one row for each survival time
tidyr::unnest(cols = c(".Surv", ".data_orig"))
} else {
idat_agd_arm <- dat_agd_arm
}
}
# Only take necessary columns
idat_agd_arm <- get_model_data_columns(idat_agd_arm,
regression = regression,
aux_regression = aux_regression,
label = "AgD (arm-based)",
keep = if (has_aux_by) aux_by else NULL)
} else {
dat_agd_arm <- idat_agd_arm <- tibble::tibble()
y_agd_arm <- NULL
}
if (has_agd_contrast(network)) {
dat_agd_contrast <- network$agd_contrast
y_agd_contrast <- get_outcome_variables(dat_agd_contrast, network$outcome$agd_contrast)
# Set up integration variables if present
if (use_int) {
idat_agd_contrast <- .unnest_integration(dat_agd_contrast)
} else {
idat_agd_contrast <- dat_agd_contrast
}
# Only take necessary columns
idat_agd_contrast <- get_model_data_columns(idat_agd_contrast,
regression = regression,
label = "AgD (contrast-based)")
# Get covariance structure for relative effects, using .se on baseline arm
Sigma_agd_contrast <- make_Sigma(dat_agd_contrast)
# Split into baseline and non-baseline arms
dat_agd_contrast_bl <- dplyr::filter(dat_agd_contrast, is.na(.data$.y))
idat_agd_contrast_bl <- dplyr::filter(idat_agd_contrast, is.na(.data$.y))
dat_agd_contrast_nonbl <- dplyr::filter(dat_agd_contrast, !is.na(.data$.y))
idat_agd_contrast_nonbl <- dplyr::filter(idat_agd_contrast, !is.na(.data$.y))
y_agd_contrast <- dplyr::filter(y_agd_contrast, !is.na(.data$.y))
} else {
dat_agd_contrast <- idat_agd_contrast <-
dat_agd_contrast_bl <- idat_agd_contrast_bl <-
dat_agd_contrast_nonbl <- idat_agd_contrast_nonbl <- tibble::tibble()
y_agd_contrast <- NULL
Sigma_agd_contrast <- NULL
}
# Combine
idat_all <- dplyr::bind_rows(dat_ipd, idat_agd_arm, idat_agd_contrast_nonbl)
idat_all_plus_bl <- dplyr::bind_rows(dat_ipd, idat_agd_arm, idat_agd_contrast)
# Get sample sizes for centering
if (((!is.null(regression) && !is_only_offset(regression)) || has_aux_regression) && center) {
# Check that required variables are present in each data set, and non-missing
if (!is.null(regression)) {
check_regression_data(regression,
dat_ipd = dat_ipd,
dat_agd_arm = idat_agd_arm,
dat_agd_contrast = idat_agd_contrast)
}
if (has_aux_regression) {
check_regression_data(aux_regression,
dat_ipd = dat_ipd,
dat_agd_arm = idat_agd_arm,
dat_agd_contrast = idat_agd_contrast)
}
# If IPD or IPD+AgD use weighted means for centering, otherwise with only AgD use raw mean
if (has_ipd(network) && (has_agd_arm(network) || has_agd_contrast(network)) && !has_agd_sample_size(network))
abort(paste("AgD study sample sizes not specified in network, cannot calculate centering values.",
"Specify `sample_size` in set_agd_*(), or set center = FALSE.", sep = "\n"))
if (has_agd_arm(network)) {
if (has_ipd(network)) {
N_agd_arm <- network$agd_arm[[".sample_size"]]
} else {
N_agd_arm <- rep(n_int, nrow(network$agd_arm))
}
} else {
N_agd_arm <- NULL
}
if (has_agd_contrast(network)) {
if (has_ipd(network)) {
N_agd_contrast <- network$agd_contrast[[".sample_size"]]
} else {
N_agd_contrast <- rep(n_int, nrow(network$agd_contrast))
}
} else {
N_agd_contrast <- NULL
}
# Apply weights across integration points
if (has_agd_arm(network) && network$outcome$agd_arm == "survival") {
wts <- c(rep(1, nrow(dat_ipd)),
rep(1 / n_int, nrow(idat_agd_arm)),
rep(N_agd_contrast / n_int, each = n_int))
} else {
wts <- c(rep(1, nrow(dat_ipd)),
rep(N_agd_arm / n_int, each = n_int),
rep(N_agd_contrast / n_int, each = n_int))
}
# Center numeric columns used in regression model
if (!is.null(regression)) {
reg_names <- all.vars(regression)
# Ignore any variable(s) used as offset(s)
reg_terms <- terms(regression)
if (length(attr(reg_terms, "offset"))) {
off_terms <- rownames(attr(reg_terms, "factors"))[attr(reg_terms, "offset")]
off_names <- all.vars(as.formula(paste("~", off_terms, sep = "+")))
reg_names <- setdiff(reg_names, off_names)
}
} else {
reg_names <- character()
}
if (has_aux_regression) {
reg_names <- unique(c(reg_names, all.vars(aux_regression)))
}
reg_numeric <- purrr::map_lgl(idat_all[, reg_names], is.numeric)
# Take weighted mean of all rows (including baseline rows for contrast data)
if (any(reg_numeric)) {
xbar <- purrr::map_dbl(idat_all_plus_bl[, reg_names[reg_numeric]], weighted.mean, w = wts)
} else {
xbar <- NULL
}
} else {
xbar <- NULL
}
# Make NMA formula
nma_formula <- make_nma_formula(regression,
consistency = consistency,
classes = !is.null(network$classes),
class_interactions = class_interactions)
# Construct model matrix
X_list <- make_nma_model_matrix(nma_formula = nma_formula,
dat_ipd = dat_ipd,
dat_agd_arm = idat_agd_arm,
dat_agd_contrast = idat_agd_contrast,
agd_contrast_bl = is.na(idat_agd_contrast$.y),
xbar = xbar,
consistency = consistency,
nodesplit = nodesplit,
classes = !is.null(network$classes))
X_ipd <- X_list$X_ipd
X_agd_arm <- X_list$X_agd_arm
X_agd_contrast <- X_list$X_agd_contrast
offset_ipd <- X_list$offset_ipd
offset_agd_arm <- X_list$offset_agd_arm
offset_agd_contrast <- X_list$offset_agd_contrast
# Construct RE correlation matrix
if (trt_effects == "random") {
# Get study/treatment data
if (has_ipd(network)) {
tdat_ipd_arm <- dplyr::distinct(dat_ipd, .data$.study, .data$.trt)
} else {
tdat_ipd_arm <- tibble::tibble()
}
if (has_agd_arm(network)) {
tdat_agd_arm <- dplyr::select(dat_agd_arm, ".study", ".trt")
} else {
tdat_agd_arm <- tibble::tibble()
}
if (has_agd_contrast(network)) {
tdat_agd_contrast_nonbl <- dplyr::select(dat_agd_contrast_nonbl, ".study", ".trt")
} else {
tdat_agd_contrast_nonbl <- tibble::tibble()
}
tdat_all <- dplyr::bind_rows(tdat_ipd_arm, tdat_agd_arm, tdat_agd_contrast_nonbl)
contr <- rep(c(FALSE, FALSE, TRUE),
times = c(nrow(tdat_ipd_arm), nrow(tdat_agd_arm), nrow(tdat_agd_contrast_nonbl)))
if (consistency %in% c("consistency", "nodesplit")) {
.RE_cor <- RE_cor(tdat_all$.study, tdat_all$.trt, contrast = contr, type = "reftrt")
.which_RE <- which_RE(tdat_all$.study, tdat_all$.trt, contrast = contr, type = "reftrt")
} else if (consistency == "ume") {
.RE_cor <- RE_cor(tdat_all$.study, tdat_all$.trt, contrast = contr, type = "blshift")
.which_RE <- which_RE(tdat_all$.study, tdat_all$.trt, contrast = contr, type = "blshift")
} else {
abort(glue::glue("Inconsistency '{consistency}' model not yet supported."))
}
} else {
.RE_cor <- NULL
.which_RE <- NULL
}
# Set up spline basis for mspline and pexp models
if (likelihood %in% c("mspline", "pexp") && (has_ipd(network) || has_agd_arm(network))) {
require_pkg("splines2")
survdat <-
if (!has_agd_arm(network)) {
dplyr::tibble(.Surv = y_ipd$.Surv,
.study = forcats::fct_drop(dat_ipd$.study),
observed = .data$.Surv[, "status"] == 1)
} else if (!has_ipd(network)) {
dplyr::tibble(.Surv = y_agd_arm$.Surv,
.study = forcats::fct_drop(rep(dat_agd_arm$.study, times = dat_agd_arm$.sample_size)),
observed = .data$.Surv[, "status"] == 1)
} else {
dplyr::tibble(.Surv = c(y_ipd$.Surv, y_agd_arm$.Surv),
.study = forcats::fct_drop(c(dat_ipd$.study, rep(dat_agd_arm$.study, times = dat_agd_arm$.sample_size))),
observed = .data$.Surv[, "status"] == 1)
}
survdat <- dplyr::mutate(survdat, !!! get_Surv_data(survdat$.Surv))
if (!is.null(mspline_basis)) {
if (!is.list(mspline_basis) || any(!purrr::map_lgl(mspline_basis, is_mspline)))
abort("`mspline_basis` must be a named list of M-spline bases created using splines2::mSpline().")
missing_names <- setdiff(levels(survdat$.study), names(mspline_basis))
if (length(missing_names) > 0)
abort(glue::glue("`mspline_basis` must be a named list of M-spline basis for each study.\n",
"Missing {if (length(missing_names) > 1) 'bases' else 'basis'} for stud{if (length(missing_names) > 1) 'ies' else 'y'} ",
glue::glue_collapse(glue::double_quote(missing_names), sep = ", ", last = " and ", width = 30), "."))
if (!all(purrr::map_int(mspline_basis, ncol) == ncol(mspline_basis[[1]])))
abort("Each basis in `mspline_basis` must currently have the same number of knots.")
if (likelihood == "pexp" && any(purrr::map_lgl(mspline_basis, ~attr(., "degree") != 0)))
abort("`mspline_basis` for piecewise exponential model must all have degree = 0.")
basis <- mspline_basis
} else {
if (likelihood == "pexp") mspline_degree <- 0
if (!rlang::is_scalar_integerish(mspline_degree, finite = TRUE) || mspline_degree < 0)
abort("`mspline_degree` must be a single non-negative integer.")
if (is.null(knots)) {
knots <- make_knots(network, n_knots = n_knots, type = if (!is.null(aux_regression)) "quantile_common" else "quantile")
} else { # User-provided knots
# Check required format
if (!has_aux_regression) {
if ((!is.list(knots) || any(!purrr::map_lgl(knots, is.numeric))) && !is.vector(knots, mode = "numeric"))
abort("`knots` must be a named list of numeric vectors giving the knot locations for each study, or a single numeric vector of knot locations to use for all studies.")
if (is.vector(knots, mode = "numeric")) {
knots <- rep_len(list(knots), dplyr::n_distinct(survdat$.study))
names(knots) <- unique(survdat$.study)
}
missing_names <- setdiff(levels(survdat$.study), names(knots))
if (length(missing_names) > 0)
abort(glue::glue("`knots` must be a named list of numeric vectors giving the knot locations for each study.\n",
"Missing knot location vector{if (length(missing_names) > 1) 's' else ''} for stud{if (length(missing_names) > 1) 'ies' else 'y'} ",
glue::glue_collapse(glue::double_quote(missing_names), sep = ", ", last = " and ", width = 30), "."))
if (!all(purrr::map_int(knots, length) == length(knots[[1]])))
abort("Each vector in `knots` must currently be the same length (each study must have the same number of knots).")
if (length(knots[[1]]) < 3)
abort("Each vector in `knots` must be at least length 3 (boundary knots and one internal knot).")
} else {
# With aux_regression, only a single vector of knot locations is allowed
if (!is.vector(knots, mode = "numeric"))
abort("`knots` must be a single numeric vector of knot locations, shared for all studies, when `aux_regression` is specified.")
if (length(knots) < 3)
abort("`knots` must be at least length 3 (boundary knots and one internal knot).")
knots <- rep_len(list(knots), dplyr::n_distinct(survdat$.study))
names(knots) <- unique(survdat$.study)
}
}
# Set up basis
# Only evaluate at first boundary knot for now to save time/memory
knots <- purrr::map(knots, sort)
knots <- tibble::as_tibble(knots)
b_knots <- knots[c(1, nrow(knots)), ]
i_knots <- knots[-c(1, nrow(knots)), ]
basis <- purrr::imap(b_knots,
~withCallingHandlers(splines2::mSpline(.x[1],
knots = i_knots[[.y]],
Boundary.knots = .x,
degree = mspline_degree,
intercept = TRUE),
error = function(e) abort(glue::glue("Could not create spline basis for study {glue::double_quote(.y)}."),
parent = e),
warning = function(w) {
warn(glue::glue("Warning while creating spline basis for study {glue::double_quote(.y)}."), parent = w)
rlang::cnd_muffle(w)
}
)
)