/
families.R
1902 lines (1755 loc) · 62.3 KB
/
families.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
#' Special Family Functions for \pkg{brms} Models
#'
#' Family objects provide a convenient way to specify the details of the models
#' used by many model fitting functions. The family functions presented here are
#' for use with \pkg{brms} only and will **not** work with other model
#' fitting functions such as \code{glm} or \code{glmer}.
#' However, the standard family functions as described in
#' \code{\link[stats:family]{family}} will work with \pkg{brms}.
#' You can also specify custom families for use in \pkg{brms} with
#' the \code{\link{custom_family}} function.
#'
#' @param family A character string naming the distribution family of the response
#' variable to be used in the model. Currently, the following families are
#' supported: \code{gaussian}, \code{student}, \code{binomial},
#' \code{bernoulli}, \code{beta-binomial}, \code{poisson}, \code{negbinomial},
#' \code{geometric}, \code{Gamma}, \code{skew_normal}, \code{lognormal},
#' \code{shifted_lognormal}, \code{exgaussian}, \code{wiener},
#' \code{inverse.gaussian}, \code{exponential}, \code{weibull},
#' \code{frechet}, \code{Beta}, \code{dirichlet}, \code{von_mises},
#' \code{asym_laplace}, \code{gen_extreme_value}, \code{categorical},
#' \code{multinomial}, \code{cumulative}, \code{cratio}, \code{sratio},
#' \code{acat}, \code{hurdle_poisson}, \code{hurdle_negbinomial},
#' \code{hurdle_gamma}, \code{hurdle_lognormal}, \code{hurdle_cumulative},
#' \code{zero_inflated_binomial}, \code{zero_inflated_beta_binomial},
#' \code{zero_inflated_beta}, \code{zero_inflated_negbinomial},
#' \code{zero_inflated_poisson}, and \code{zero_one_inflated_beta}.
#' @param link A specification for the model link function. This can be a
#' name/expression or character string. See the 'Details' section for more
#' information on link functions supported by each family.
#' @param link_sigma Link of auxiliary parameter \code{sigma} if being predicted.
#' @param link_shape Link of auxiliary parameter \code{shape} if being predicted.
#' @param link_nu Link of auxiliary parameter \code{nu} if being predicted.
#' @param link_phi Link of auxiliary parameter \code{phi} if being predicted.
#' @param link_kappa Link of auxiliary parameter \code{kappa} if being predicted.
#' @param link_beta Link of auxiliary parameter \code{beta} if being predicted.
#' @param link_zi Link of auxiliary parameter \code{zi} if being predicted.
#' @param link_hu Link of auxiliary parameter \code{hu} if being predicted.
#' @param link_zoi Link of auxiliary parameter \code{zoi} if being predicted.
#' @param link_coi Link of auxiliary parameter \code{coi} if being predicted.
#' @param link_disc Link of auxiliary parameter \code{disc} if being predicted.
#' @param link_bs Link of auxiliary parameter \code{bs} if being predicted.
#' @param link_ndt Link of auxiliary parameter \code{ndt} if being predicted.
#' @param link_bias Link of auxiliary parameter \code{bias} if being predicted.
#' @param link_alpha Link of auxiliary parameter \code{alpha} if being predicted.
#' @param link_quantile Link of auxiliary parameter \code{quantile} if being predicted.
#' @param link_xi Link of auxiliary parameter \code{xi} if being predicted.
#' @param threshold A character string indicating the type
#' of thresholds (i.e. intercepts) used in an ordinal model.
#' \code{"flexible"} provides the standard unstructured thresholds,
#' \code{"equidistant"} restricts the distance between
#' consecutive thresholds to the same value, and
#' \code{"sum_to_zero"} ensures the thresholds sum to zero.
#' @param refcat Optional name of the reference response category used in
#' \code{categorical}, \code{multinomial}, \code{dirichlet} and
#' \code{logistic_normal} models. If \code{NULL} (the default), the first
#' category is used as the reference. If \code{NA}, all categories will be
#' predicted, which requires strong priors or carefully specified predictor
#' terms in order to lead to an identified model.
#' @param bhaz Currently for experimental purposes only.
#'
#' @details
#' Below, we list common use cases for the different families.
#' This list is not ment to be exhaustive.
#' \itemize{
#' \item{Family \code{gaussian} can be used for linear regression.}
#'
#' \item{Family \code{student} can be used for robust linear regression
#' that is less influenced by outliers.}
#'
#' \item{Family \code{skew_normal} can handle skewed responses in linear
#' regression.}
#'
#' \item{Families \code{poisson}, \code{negbinomial}, and \code{geometric}
#' can be used for regression of unbounded count data.}
#'
#' \item{Families \code{bernoulli}, \code{binomial}, and \code{beta_binomial}
#' can be used for binary regression (i.e., most commonly logistic
#' regression).}
#'
#' \item{Families \code{categorical} and \code{multinomial} can be used for
#' multi-logistic regression when there are more than two possible outcomes.}
#'
#' \item{Families \code{cumulative}, \code{cratio} ('continuation ratio'),
#' \code{sratio} ('stopping ratio'), and \code{acat} ('adjacent category')
#' leads to ordinal regression.}
#'
#' \item{Families \code{Gamma}, \code{weibull}, \code{exponential},
#' \code{lognormal}, \code{frechet}, \code{inverse.gaussian}, and \code{cox}
#' (Cox proportional hazards model) can be used (among others) for
#' time-to-event regression also known as survival regression.}
#'
#' \item{Families \code{weibull}, \code{frechet}, and \code{gen_extreme_value}
#' ('generalized extreme value') allow for modeling extremes.}
#'
#' \item{Families \code{beta}, \code{dirichlet}, and \code{logistic_normal}
#' can be used to model responses representing rates or probabilities.}
#'
#' \item{Family \code{asym_laplace} allows for quantile regression when fixing
#' the auxiliary \code{quantile} parameter to the quantile of interest.}
#'
#' \item{Family \code{exgaussian} ('exponentially modified Gaussian') and
#' \code{shifted_lognormal} are especially suited to model reaction times.}
#'
#' \item{Family \code{wiener} provides an implementation of the Wiener
#' diffusion model. For this family, the main formula predicts the drift
#' parameter 'delta' and all other parameters are modeled as auxiliary parameters
#' (see \code{\link{brmsformula}} for details).}
#'
#' \item{Families \code{hurdle_poisson}, \code{hurdle_negbinomial},
#' \code{hurdle_gamma}, \code{hurdle_lognormal}, \code{zero_inflated_poisson},
#' \code{zero_inflated_negbinomial}, \code{zero_inflated_binomial},
#' \code{zero_inflated_beta_binomial}, \code{zero_inflated_beta},
#' \code{zero_one_inflated_beta}, and \code{hurdle_cumulative} allow to estimate
#' zero-inflated and hurdle models. These models can be very helpful when there
#' are many zeros in the data (or ones in case of one-inflated models)
#' that cannot be explained by the primary distribution of the response.}
#' }
#'
#' Below, we list all possible links for each family.
#' The first link mentioned for each family is the default.
#' \itemize{
#' \item{Families \code{gaussian}, \code{student}, \code{skew_normal},
#' \code{exgaussian}, \code{asym_laplace}, and \code{gen_extreme_value}
#' support the links (as names) \code{identity}, \code{log}, \code{inverse},
#' and \code{softplus}.}
#'
#' \item{Families \code{poisson}, \code{negbinomial}, \code{geometric},
#' \code{zero_inflated_poisson}, \code{zero_inflated_negbinomial},
#' \code{hurdle_poisson}, and \code{hurdle_negbinomial} support
#' \code{log}, \code{identity}, \code{sqrt}, and \code{softplus}.}
#'
#' \item{Families \code{binomial}, \code{bernoulli}, \code{beta_binomial},
#' \code{zero_inflated_binomial}, \code{zero_inflated_beta_binomial},
#' \code{Beta}, \code{zero_inflated_beta}, and \code{zero_one_inflated_beta}
#' support \code{logit}, \code{probit}, \code{probit_approx}, \code{cloglog},
#' \code{cauchit}, \code{identity}, and \code{log}.}
#'
#' \item{Families \code{cumulative}, \code{cratio}, \code{sratio},
#' \code{acat}, and \code{hurdle_cumulative} support \code{logit},
#' \code{probit}, \code{probit_approx}, \code{cloglog}, and \code{cauchit}.}
#'
#' \item{Families \code{categorical}, \code{multinomial}, and \code{dirichlet}
#' support \code{logit}.}
#'
#' \item{Families \code{Gamma}, \code{weibull}, \code{exponential},
#' \code{frechet}, and \code{hurdle_gamma} support
#' \code{log}, \code{identity}, \code{inverse}, and \code{softplus}.}
#'
#' \item{Families \code{lognormal} and \code{hurdle_lognormal}
#' support \code{identity} and \code{inverse}.}
#'
#' \item{Family \code{logistic_normal} supports \code{identity}.}
#'
#' \item{Family \code{inverse.gaussian} supports \code{1/mu^2},
#' \code{inverse}, \code{identity}, \code{log}, and \code{softplus}.}
#'
#' \item{Family \code{von_mises} supports \code{tan_half} and
#' \code{identity}.}
#'
#' \item{Family \code{cox} supports \code{log}, \code{identity},
#' and \code{softplus} for the proportional hazards parameter.}
#'
#' \item{Family \code{wiener} supports \code{identity}, \code{log},
#' and \code{softplus} for the main parameter which represents the
#' drift rate.}
#' }
#'
#' Please note that when calling the \code{\link[stats:family]{Gamma}} family
#' function of the \pkg{stats} package, the default link will be
#' \code{inverse} instead of \code{log} although the latter is the default in
#' \pkg{brms}. Also, when using the family functions \code{gaussian},
#' \code{binomial}, \code{poisson}, and \code{Gamma} of the \pkg{stats}
#' package (see \code{\link[stats:family]{family}}), special link functions
#' such as \code{softplus} or \code{cauchit} won't work. In this case, you
#' have to use \code{brmsfamily} to specify the family with corresponding link
#' function.
#'
#' @seealso \code{\link[brms:brm]{brm}},
#' \code{\link[stats:family]{family}},
#' \code{\link{customfamily}}
#'
#' @examples
#' # create a family object
#' (fam1 <- student("log"))
#' # alternatively use the brmsfamily function
#' (fam2 <- brmsfamily("student", "log"))
#' # both leads to the same object
#' identical(fam1, fam2)
#'
#' @export
brmsfamily <- function(family, link = NULL, link_sigma = "log",
link_shape = "log", link_nu = "logm1",
link_phi = "log", link_kappa = "log",
link_beta = "log", link_zi = "logit",
link_hu = "logit", link_zoi = "logit",
link_coi = "logit", link_disc = "log",
link_bs = "log", link_ndt = "log",
link_bias = "logit", link_xi = "log1p",
link_alpha = "identity",
link_quantile = "logit",
threshold = "flexible",
refcat = NULL, bhaz = NULL) {
slink <- substitute(link)
.brmsfamily(
family, link = link, slink = slink,
link_sigma = link_sigma, link_shape = link_shape,
link_nu = link_nu, link_phi = link_phi,
link_kappa = link_kappa, link_beta = link_beta,
link_zi = link_zi, link_hu = link_hu,
link_zoi = link_zoi, link_coi = link_coi,
link_disc = link_disc, link_bs = link_bs,
link_ndt = link_ndt, link_bias = link_bias,
link_alpha = link_alpha, link_xi = link_xi,
link_quantile = link_quantile,
threshold = threshold, refcat = refcat,
bhaz = bhaz
)
}
# helper function to prepare brmsfamily objects
# @param family character string naming the model family
# @param link character string naming the link function
# @param slink can be used with substitute(link) for
# non-standard evaluation of the link function
# @param threshold threshold type for ordinal models
# @param ... link functions (as character strings) of parameters
# @return an object of 'brmsfamily' which inherits from 'family'
.brmsfamily <- function(family, link = NULL, slink = link,
threshold = "flexible",
refcat = NULL, bhaz = NULL, ...) {
family <- tolower(as_one_character(family))
aux_links <- list(...)
pattern <- c("^normal$", "^zi_", "^hu_")
replacement <- c("gaussian", "zero_inflated_", "hurdle_")
family <- rename(family, pattern, replacement, fixed = FALSE)
ok_families <- lsp("brms", pattern = "^\\.family_")
ok_families <- sub("^\\.family_", "", ok_families)
if (!family %in% ok_families) {
stop2(family, " is not a supported family. Supported ",
"families are:\n", collapse_comma(ok_families))
}
family_info <- get(paste0(".family_", family))()
ok_links <- family_info$links
family_info$links <- NULL
# non-standard evaluation of link
if (!is.character(slink)) {
slink <- deparse0(slink)
}
if (!slink %in% ok_links) {
if (is.character(link)) {
slink <- link
} else if (!length(link) || identical(link, NA)) {
slink <- NA
}
}
if (length(slink) != 1L) {
stop2("Argument 'link' must be of length 1.")
}
if (is.na(slink)) {
slink <- ok_links[1]
}
if (!slink %in% ok_links) {
stop2("'", slink, "' is not a supported link ",
"for family '", family, "'.\nSupported links are: ",
collapse_comma(ok_links))
}
out <- list(
family = family, link = slink,
linkfun = function(mu) link(mu, link = slink),
linkinv = function(eta) inv_link(eta, link = slink)
)
out[names(family_info)] <- family_info
class(out) <- c("brmsfamily", "family")
all_valid_dpars <- c(valid_dpars(out), valid_dpars(out, type = "multi"))
for (dp in all_valid_dpars) {
alink <- as.character(aux_links[[paste0("link_", dp)]])
if (length(alink)) {
alink <- as_one_character(alink)
valid_links <- links_dpars(dp)
if (!alink %in% valid_links) {
stop2(
"'", alink, "' is not a supported link ",
"for parameter '", dp, "'.\nSupported links are: ",
collapse_comma(valid_links)
)
}
out[[paste0("link_", dp)]] <- alink
}
}
if (is_ordinal(out$family)) {
# TODO: move specification of 'threshold' to the 'resp_thres' function?
thres_options <- c("flexible", "equidistant", "sum_to_zero")
out$threshold <- match.arg(threshold, thres_options)
}
if (conv_cats_dpars(out$family)) {
if (!has_joint_link(out$family)) {
out$refcat <- NA
} else if (!is.null(refcat)) {
allow_na_ref <- !is_logistic_normal(out$family)
out$refcat <- as_one_character(refcat, allow_na = allow_na_ref)
}
}
if (is_cox(out$family)) {
if (!is.null(bhaz)) {
if (!is.list(bhaz)) {
stop2("'bhaz' should be a list.")
}
out$bhaz <- bhaz
} else {
out$bhaz <- list()
}
# set default arguments
if (is.null(out$bhaz$df)) {
out$bhaz$df <- 5L
}
if (is.null(out$bhaz$intercept)) {
out$bhaz$intercept <- TRUE
}
}
out
}
# checks and corrects validity of the model family
# @param family Either a function, an object of class 'family'
# or a character string of length one or two
# @param link an optional character string naming the link function
# ignored if family is a function or a family object
# @param threshold optional character string specifying the threshold
# type in ordinal models
validate_family <- function(family, link = NULL, threshold = NULL) {
if (is.function(family)) {
family <- family()
}
if (!is(family, "brmsfamily")) {
if (is.family(family)) {
link <- family$link
family <- family$family
}
if (is.character(family)) {
if (is.null(link)) {
link <- family[2]
}
family <- .brmsfamily(family[1], link = link)
} else {
stop2("Argument 'family' is invalid.")
}
}
if (is_ordinal(family) && !is.null(threshold)) {
# slot 'threshold' deprecated as of brms > 1.7.0
threshold <- match.arg(threshold, c("flexible", "equidistant"))
family$threshold <- threshold
}
family
}
# extract special information of families
# @param x object from which to extract
# @param y name of the component to extract
family_info <- function(x, y, ...) {
UseMethod("family_info")
}
#' @export
family_info.default <- function(x, y, ...) {
x <- as.character(x)
ulapply(x, .family_info, y = y, ...)
}
.family_info <- function(x, y, ...) {
x <- as_one_character(x)
y <- as_one_character(y)
if (y == "family") {
return(x)
}
if (!nzchar(x)) {
return(NULL)
}
info <- get(paste0(".family_", x))()
if (y == "link") {
out <- info$links[1] # default link
} else {
info$links <- NULL
out <- info[[y]]
}
out
}
#' @export
family_info.NULL <- function(x, y, ...) {
NULL
}
#' @export
family_info.list <- function(x, y, ...) {
ulapply(x, family_info, y = y, ...)
}
#' @export
family_info.family <- function(x, y, ...) {
family_info(x$family, y = y, ...)
}
#' @export
family_info.brmsfamily <- function(x, y, ...) {
y <- as_one_character(y)
out <- x[[y]]
if (is.null(out)) {
# required for models fitted with brms 2.2 or earlier
out <- family_info(x$family, y = y, ...)
}
out
}
#' @export
family_info.mixfamily <- function(x, y, ...) {
out <- lapply(x$mix, family_info, y = y, ...)
combine_family_info(out, y = y)
}
#' @export
family_info.brmsformula <- function(x, y, ...) {
family_info(x$family, y = y, ...)
}
#' @export
family_info.mvbrmsformula <- function(x, y, ...) {
out <- lapply(x$forms, family_info, y = y, ...)
combine_family_info(out, y = y)
}
#' @export
family_info.brmsterms <- function(x, y, ...) {
family_info(x$family, y = y, ...)
}
#' @export
family_info.mvbrmsterms <- function(x, y, ...) {
out <- lapply(x$terms, family_info, y = y, ...)
combine_family_info(out, y = y)
}
#' @export
family_info.btl <- function(x, y, ...) {
family_info(x$family, y = y, ...)
}
#' @export
family_info.btnl <- function(x, y, ...) {
family_info(x$family, y = y, ...)
}
#' @export
family_info.brmsfit <- function(x, y, ...) {
family_info(x$formula, y = y, ...)
}
# combine information from multiple families
# provides special handling for certain elements
combine_family_info <- function(x, y, ...) {
y <- as_one_character(y)
unite <- c(
"dpars", "type", "specials", "include",
"const", "cats", "ad", "normalized"
)
if (y %in% c("family", "link")) {
x <- unlist(x)
} else if (y %in% unite) {
x <- Reduce("union", x)
} else if (y == "ybounds") {
x <- do_call(rbind, x)
x <- c(max(x[, 1]), min(x[, 2]))
} else if (y == "closed") {
# closed only if no bounds are open
x <- do_call(rbind, x)
clb <- !any(ulapply(x[, 1], isFALSE))
cub <- !any(ulapply(x[, 2], isFALSE))
x <- c(clb, cub)
} else if (y == "thres") {
# thresholds are the same across mixture components
x <- x[[1]]
}
x
}
#' @rdname brmsfamily
#' @export
student <- function(link = "identity", link_sigma = "log", link_nu = "logm1") {
slink <- substitute(link)
.brmsfamily("student", link = link, slink = slink,
link_sigma = link_sigma, link_nu = link_nu)
}
#' @rdname brmsfamily
#' @export
bernoulli <- function(link = "logit") {
slink <- substitute(link)
.brmsfamily("bernoulli", link = link, slink = slink)
}
#' @rdname brmsfamily
#' @export
beta_binomial <- function(link = "logit", link_phi = "log") {
slink <- substitute(link)
.brmsfamily("beta_binomial", link = link, slink = slink, link_phi = link_phi)
}
#' @rdname brmsfamily
#' @export
negbinomial <- function(link = "log", link_shape = "log") {
slink <- substitute(link)
.brmsfamily("negbinomial", link = link, slink = slink,
link_shape = link_shape)
}
# not yet officially supported
# @rdname brmsfamily
# @export
negbinomial2 <- function(link = "log", link_sigma = "log") {
slink <- substitute(link)
.brmsfamily("negbinomial2", link = link, slink = slink,
link_sigma = link_sigma)
}
#' @rdname brmsfamily
#' @export
geometric <- function(link = "log") {
slink <- substitute(link)
.brmsfamily("geometric", link = link, slink = slink)
}
# do not export yet!
# @rdname brmsfamily
# @export
discrete_weibull <- function(link = "logit", link_shape = "log") {
slink <- substitute(link)
.brmsfamily("discrete_weibull", link = link, slink = slink,
link_shape = link_shape)
}
# do not export yet!
# @rdname brmsfamily
# @export
com_poisson <- function(link = "log", link_shape = "log") {
slink <- substitute(link)
.brmsfamily("com_poisson", link = link, slink = slink,
link_shape = link_shape)
}
#' @rdname brmsfamily
#' @export
lognormal <- function(link = "identity", link_sigma = "log") {
slink <- substitute(link)
.brmsfamily("lognormal", link = link, slink = slink,
link_sigma = link_sigma)
}
#' @rdname brmsfamily
#' @export
shifted_lognormal <- function(link = "identity", link_sigma = "log",
link_ndt = "log") {
slink <- substitute(link)
.brmsfamily("shifted_lognormal", link = link, slink = slink,
link_sigma = link_sigma, link_ndt = link_ndt)
}
#' @rdname brmsfamily
#' @export
skew_normal <- function(link = "identity", link_sigma = "log",
link_alpha = "identity") {
slink <- substitute(link)
.brmsfamily("skew_normal", link = link, slink = slink,
link_sigma = link_sigma, link_alpha = link_alpha)
}
#' @rdname brmsfamily
#' @export
exponential <- function(link = "log") {
slink <- substitute(link)
.brmsfamily("exponential", link = link, slink = slink)
}
#' @rdname brmsfamily
#' @export
weibull <- function(link = "log", link_shape = "log") {
slink <- substitute(link)
.brmsfamily("weibull", link = link, slink = slink,
link_shape = link_shape)
}
#' @rdname brmsfamily
#' @export
frechet <- function(link = "log", link_nu = "logm1") {
slink <- substitute(link)
.brmsfamily("frechet", link = link, slink = slink,
link_nu = link_nu)
}
#' @rdname brmsfamily
#' @export
gen_extreme_value <- function(link = "identity", link_sigma = "log",
link_xi = "log1p") {
slink <- substitute(link)
.brmsfamily("gen_extreme_value", link = link, slink = slink,
link_sigma = link_sigma, link_xi = link_xi)
}
#' @rdname brmsfamily
#' @export
exgaussian <- function(link = "identity", link_sigma = "log",
link_beta = "log") {
slink <- substitute(link)
.brmsfamily("exgaussian", link = link, slink = slink,
link_sigma = link_sigma, link_beta = link_beta)
}
#' @rdname brmsfamily
#' @export
wiener <- function(link = "identity", link_bs = "log",
link_ndt = "log", link_bias = "logit") {
slink <- substitute(link)
.brmsfamily("wiener", link = link, slink = slink,
link_bs = link_bs, link_ndt = link_ndt,
link_bias = link_bias)
}
#' @rdname brmsfamily
#' @export
Beta <- function(link = "logit", link_phi = "log") {
slink <- substitute(link)
.brmsfamily("beta", link = link, slink = slink,
link_phi = link_phi)
}
#' @rdname brmsfamily
#' @export
dirichlet <- function(link = "logit", link_phi = "log", refcat = NULL) {
slink <- substitute(link)
.brmsfamily("dirichlet", link = link, slink = slink,
link_phi = link_phi, refcat = refcat)
}
# not yet exported
# @rdname brmsfamily
# @export
dirichlet2 <- function(link = "log") {
slink <- substitute(link)
.brmsfamily("dirichlet2", link = link, slink = slink, refcat = NA)
}
#' @rdname brmsfamily
#' @export
logistic_normal <- function(link = "identity", link_sigma = "log",
refcat = NULL) {
slink <- substitute(link)
.brmsfamily("logistic_normal", link = link, slink = slink,
link_sigma = link_sigma, refcat = refcat)
}
#' @rdname brmsfamily
#' @export
von_mises <- function(link = "tan_half", link_kappa = "log") {
slink <- substitute(link)
.brmsfamily("von_mises", link = link, slink = slink,
link_kappa = link_kappa)
}
#' @rdname brmsfamily
#' @export
asym_laplace <- function(link = "identity", link_sigma = "log",
link_quantile = "logit") {
slink <- substitute(link)
.brmsfamily("asym_laplace", link = link, slink = slink,
link_sigma = link_sigma, link_quantile = link_quantile)
}
# do not export yet!
# @rdname brmsfamily
# @export
zero_inflated_asym_laplace <- function(link = "identity", link_sigma = "log",
link_quantile = "logit",
link_zi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_inflated_asym_laplace", link = link, slink = slink,
link_sigma = link_sigma, link_quantile = link_quantile,
link_zi = link_zi)
}
#' @rdname brmsfamily
#' @export
cox <- function(link = "log", bhaz = NULL) {
slink <- substitute(link)
.brmsfamily("cox", link = link, bhaz = bhaz)
}
#' @rdname brmsfamily
#' @export
hurdle_poisson <- function(link = "log", link_hu = "logit") {
slink <- substitute(link)
.brmsfamily("hurdle_poisson", link = link, slink = slink,
link_hu = link_hu)
}
#' @rdname brmsfamily
#' @export
hurdle_negbinomial <- function(link = "log", link_shape = "log",
link_hu = "logit") {
slink <- substitute(link)
.brmsfamily("hurdle_negbinomial", link = link, slink = slink,
link_shape = link_shape, link_hu = link_hu)
}
#' @rdname brmsfamily
#' @export
hurdle_gamma <- function(link = "log", link_shape = "log",
link_hu = "logit") {
slink <- substitute(link)
.brmsfamily("hurdle_gamma", link = link, slink = slink,
link_shape = link_shape, link_hu = link_hu)
}
#' @rdname brmsfamily
#' @export
hurdle_lognormal <- function(link = "identity", link_sigma = "log",
link_hu = "logit") {
slink <- substitute(link)
.brmsfamily("hurdle_lognormal", link = link, slink = slink,
link_sigma = link_sigma, link_hu = link_hu)
}
#' @rdname brmsfamily
#' @export
hurdle_cumulative <- function(link = "logit", link_hu = "logit",
link_disc = "log", threshold = "flexible") {
slink <- substitute(link)
.brmsfamily("hurdle_cumulative", link = link, slink = slink,
link_hu = link_hu, link_disc = link_disc,
threshold = threshold)
}
#' @rdname brmsfamily
#' @export
zero_inflated_beta <- function(link = "logit", link_phi = "log",
link_zi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_inflated_beta", link = link, slink = slink,
link_phi = link_phi, link_zi = link_zi)
}
#' @rdname brmsfamily
#' @export
zero_one_inflated_beta <- function(link = "logit", link_phi = "log",
link_zoi = "logit", link_coi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_one_inflated_beta", link = link, slink = slink,
link_phi = link_phi, link_zoi = link_zoi,
link_coi = link_coi)
}
#' @rdname brmsfamily
#' @export
zero_inflated_poisson <- function(link = "log", link_zi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_inflated_poisson", link = link, slink = slink,
link_zi = link_zi)
}
#' @rdname brmsfamily
#' @export
zero_inflated_negbinomial <- function(link = "log", link_shape = "log",
link_zi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_inflated_negbinomial", link = link, slink = slink,
link_shape = link_shape, link_zi = link_zi)
}
#' @rdname brmsfamily
#' @export
zero_inflated_binomial <- function(link = "logit", link_zi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_inflated_binomial", link = link, slink = slink,
link_zi = link_zi)
}
#' @rdname brmsfamily
#' @export
zero_inflated_beta_binomial <- function(link = "logit", link_phi = "log",
link_zi = "logit") {
slink <- substitute(link)
.brmsfamily("zero_inflated_beta_binomial", link = link, slink = slink,
link_phi = link_phi, link_zi = link_zi)
}
#' @rdname brmsfamily
#' @export
categorical <- function(link = "logit", refcat = NULL) {
slink <- substitute(link)
.brmsfamily("categorical", link = link, slink = slink, refcat = refcat)
}
#' @rdname brmsfamily
#' @export
multinomial <- function(link = "logit", refcat = NULL) {
slink <- substitute(link)
.brmsfamily("multinomial", link = link, slink = slink, refcat = refcat)
}
#' @rdname brmsfamily
#' @export
cumulative <- function(link = "logit", link_disc = "log",
threshold = "flexible") {
slink <- substitute(link)
.brmsfamily("cumulative", link = link, slink = slink,
link_disc = link_disc, threshold = threshold)
}
#' @rdname brmsfamily
#' @export
sratio <- function(link = "logit", link_disc = "log",
threshold = "flexible") {
slink <- substitute(link)
.brmsfamily("sratio", link = link, slink = slink,
link_disc = link_disc, threshold = threshold)
}
#' @rdname brmsfamily
#' @export
cratio <- function(link = "logit", link_disc = "log",
threshold = "flexible") {
slink <- substitute(link)
.brmsfamily("cratio", link = link, slink = slink,
link_disc = link_disc, threshold = threshold)
}
#' @rdname brmsfamily
#' @export
acat <- function(link = "logit", link_disc = "log",
threshold = "flexible") {
slink <- substitute(link)
.brmsfamily("acat", link = link, slink = slink,
link_disc = link_disc, threshold = threshold)
}
#' Finite Mixture Families in \pkg{brms}
#'
#' Set up a finite mixture family for use in \pkg{brms}.
#'
#' @param ... One or more objects providing a description of the
#' response distributions to be combined in the mixture model.
#' These can be family functions, calls to family functions or
#' character strings naming the families. For details of supported
#' families see \code{\link{brmsfamily}}.
#' @param flist Optional list of objects, which are treated in the
#' same way as objects passed via the \code{...} argument.
#' @param nmix Optional numeric vector specifying the number of times
#' each family is repeated. If specified, it must have the same length
#' as the number of families passed via \code{...} and \code{flist}.
#' @param order Ordering constraint to identify mixture components.
#' If \code{'mu'} or \code{TRUE}, population-level intercepts
#' of the mean parameters are ordered in non-ordinal models
#' and fixed to the same value in ordinal models (see details).
#' If \code{'none'} or \code{FALSE}, no ordering constraint is applied.
#' If \code{NULL} (the default), \code{order} is set to \code{'mu'}
#' if all families are the same and \code{'none'} otherwise.
#' Other ordering constraints may be implemented in the future.
#'
#' @return An object of class \code{mixfamily}.
#'
#' @details
#'
#' Most families supported by \pkg{brms} can be used to form mixtures. The
#' response variable has to be valid for all components of the mixture family.
#' Currently, the number of mixture components has to be specified by the user.
#' It is not yet possible to estimate the number of mixture components from the
#' data.
#'
#' Ordering intercepts in mixtures of ordinal families is not possible as each
#' family has itself a set of vector of intercepts (i.e. ordinal thresholds).
#' Instead, \pkg{brms} will fix the vector of intercepts across components in
#' ordinal mixtures, if desired, so that users can try to identify the mixture
#' model via selective inclusion of predictors.
#'
#' For most mixture models, you may want to specify priors on the
#' population-level intercepts via \code{\link{set_prior}} to improve
#' convergence. In addition, it is sometimes necessary to set \code{init = 0}
#' in the call to \code{\link{brm}} to allow chains to initialize properly.
#'
#' For more details on the specification of mixture
#' models, see \code{\link{brmsformula}}.
#'
#' @examples
#' \dontrun{
#' ## simulate some data
#' set.seed(1234)
#' dat <- data.frame(
#' y = c(rnorm(200), rnorm(100, 6)),
#' x = rnorm(300),
#' z = sample(0:1, 300, TRUE)
#' )
#'
#' ## fit a simple normal mixture model
#' mix <- mixture(gaussian, gaussian)
#' prior <- c(
#' prior(normal(0, 7), Intercept, dpar = mu1),
#' prior(normal(5, 7), Intercept, dpar = mu2)
#' )
#' fit1 <- brm(bf(y ~ x + z), dat, family = mix,
#' prior = prior, chains = 2)
#' summary(fit1)
#' pp_check(fit1)
#'
#' ## use different predictors for the components
#' fit2 <- brm(bf(y ~ 1, mu1 ~ x, mu2 ~ z), dat, family = mix,
#' prior = prior, chains = 2)
#' summary(fit2)
#'
#' ## fix the mixing proportions
#' fit3 <- brm(bf(y ~ x + z, theta1 = 1, theta2 = 2),
#' dat, family = mix, prior = prior,
#' init = 0, chains = 2)
#' summary(fit3)
#' pp_check(fit3)
#'
#' ## predict the mixing proportions
#' fit4 <- brm(bf(y ~ x + z, theta2 ~ x),
#' dat, family = mix, prior = prior,
#' init = 0, chains = 2)
#' summary(fit4)
#' pp_check(fit4)
#'
#' ## compare model fit
#' loo(fit1, fit2, fit3, fit4)
#' }
#'
#' @export
mixture <- function(..., flist = NULL, nmix = 1, order = NULL) {
dots <- c(list(...), flist)
if (length(nmix) == 1L) {
nmix <- rep(nmix, length(dots))
}
if (length(dots) != length(nmix)) {
stop2("The length of 'nmix' should be the same ",
"as the number of mixture components.")
}
dots <- dots[rep(seq_along(dots), nmix)]
family <- list(
family = "mixture",
link = "identity",
mix = lapply(dots, validate_family)
)
class(family) <- c("mixfamily", "brmsfamily", "family")
# validity checks
if (length(family$mix) < 2L) {
stop2("Expecting at least 2 mixture components.")
}
if (use_real(family) && use_int(family)) {
stop2("Cannot mix families with real and integer support.")
}
is_ordinal <- ulapply(family$mix, is_ordinal)
if (any(is_ordinal) && any(!is_ordinal)) {
stop2("Cannot mix ordinal and non-ordinal families.")
}
no_mixture <- ulapply(family$mix, no_mixture)
if (any(no_mixture)) {
stop2("Some of the families are not allowed in mixture models.")
}
for (fam in family$mix) {
if (is.customfamily(fam) && "theta" %in% fam$dpars) {
stop2("Parameter name 'theta' is reserved in mixture models.")
}
}
if (is.null(order)) {
if (any(is_ordinal)) {
family$order <- "none"
message("Setting order = 'none' for mixtures of ordinal families.")
} else if (length(unique(family_names(family))) == 1L) {
family$order <- "mu"
message("Setting order = 'mu' for mixtures of the same family.")
} else {
family$order <- "none"
message("Setting order = 'none' for mixtures of different families.")
}
} else {
if (length(order) != 1L) {
stop2("Argument 'order' must be of length 1.")
}
if (is.character(order)) {
valid_order <- c("none", "mu")
if (!order %in% valid_order) {
stop2("Argument 'order' is invalid. Valid options are: ",
collapse_comma(valid_order))
}
family$order <- order
} else {
family$order <- ifelse(as.logical(order), "mu", "none")
}
}
family
}
#' Custom Families in \pkg{brms} Models