File: methods_BayesFactor.R

package info (click to toggle)
r-cran-parameters 0.24.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,852 kB
  • sloc: sh: 16; makefile: 2
file content (297 lines) | stat: -rw-r--r-- 9,193 bytes parent folder | download
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
# classes: .BFBayesFactor


#' Parameters from BayesFactor objects
#'
#' Parameters from `BFBayesFactor` objects from `{BayesFactor}` package.
#'
#' @param model Object of class `BFBayesFactor`.
#' @param include_proportions Logical that decides whether to include posterior
#'   cell proportions/counts for Bayesian contingency table analysis (from
#'   `BayesFactor::contingencyTableBF()`). Defaults to `FALSE`, as this
#'   information is often redundant.
#' @inheritParams bayestestR::describe_posterior
#' @inheritParams p_value
#' @inheritParams model_parameters.htest
#'
#' @details
#' The meaning of the extracted parameters:
#'
#' - For [BayesFactor::ttestBF()]: `Difference` is the raw difference between
#'   the means.
#' - For [BayesFactor::correlationBF()]: `rho` is the linear correlation
#'   estimate (equivalent to Pearson's *r*).
#' - For [BayesFactor::lmBF()] / [BayesFactor::generalTestBF()]
#'   / [BayesFactor::regressionBF()] / [BayesFactor::anovaBF()]: in addition to
#'   parameters of the fixed and random effects, there are: `mu` is the
#'   (mean-centered) intercept; `sig2` is the model's sigma; `g` / `g_*` are
#'   the *g* parameters; See the *Bayes Factors for ANOVAs* paper
#'   (\doi{10.1016/j.jmp.2012.08.001}).
#'
#' @examplesIf require("BayesFactor")
#' \donttest{
#' # Bayesian t-test
#' model <- BayesFactor::ttestBF(x = rnorm(100, 1, 1))
#' model_parameters(model)
#' model_parameters(model, es_type = "cohens_d", ci = 0.9)
#'
#' # Bayesian contingency table analysis
#' data(raceDolls)
#' bf <- BayesFactor::contingencyTableBF(
#'   raceDolls,
#'   sampleType = "indepMulti",
#'   fixedMargin = "cols"
#' )
#' model_parameters(bf,
#'   centrality = "mean",
#'   dispersion = TRUE,
#'   verbose = FALSE,
#'   es_type = "cramers_v"
#' )
#' }
#' @return A data frame of indices related to the model's parameters.
#' @export
model_parameters.BFBayesFactor <- function(model,
                                           centrality = "median",
                                           dispersion = FALSE,
                                           ci = 0.95,
                                           ci_method = "eti",
                                           test = "pd",
                                           rope_range = "default",
                                           rope_ci = 0.95,
                                           priors = TRUE,
                                           es_type = NULL,
                                           include_proportions = FALSE,
                                           verbose = TRUE,
                                           ...) {
  insight::check_if_installed("BayesFactor")

  if (any(startsWith(names(model@numerator), "Null"))) {
    if (isTRUE(verbose)) {
      insight::format_alert(
        "Nothing to compute for point-null models.",
        "See github.com/easystats/parameters/issues/226"
      )
    }
    return(NULL)
  }

  if (is.null(insight::get_parameters(model, verbose = FALSE))) {
    if (isTRUE(verbose)) {
      insight::format_warning("Can't extract model parameters.")
    }
    return(NULL)
  }

  out <- bayestestR::describe_posterior(
    model,
    centrality = centrality,
    dispersion = dispersion,
    ci = ci,
    ci_method = ci_method,
    test = test,
    rope_range = rope_range,
    rope_ci = rope_ci,
    priors = priors,
    verbose = verbose,
    ...
  )

  bf_type <- .classify_BFBayesFactor(model)

  # Add components and effects columns
  cleaned_params <- NULL
  out <- tryCatch(
    {
      cleaned_params <- insight::clean_parameters(model)
      merge(out, cleaned_params[, c("Parameter", "Effects", "Component")], sort = FALSE)
    },
    error = function(e) {
      out
    }
  )

  # Extract BF
  tryCatch(
    {
      bfm <- as.data.frame(bayestestR::bayesfactor_models(model)[-1, ])
      if (is.null(bfm$log_BF)) {
        out$BF <- bfm$BF
      } else {
        out$BF <- exp(bfm$log_BF)
      }
    },
    error = function(e) {
      NULL
    }
  )

  # leave out redundant posterior cell proportions/counts
  if (bf_type == "xtable" && isFALSE(include_proportions)) {
    out <- out[which(!startsWith(out$Parameter, "cell[")), , drop = FALSE]
  }

  # Effect size?
  if (!is.null(es_type)) {
    # needs {effectsize} to be installed
    insight::check_if_installed("effectsize")

    tryCatch(
      {
        effsize <- effectsize::effectsize(model,
          centrality = centrality,
          dispersion = dispersion,
          ci = ci,
          ci_method = ci_method,
          rope_ci = rope_ci,
          type = es_type,
          ...
        )

        if (bf_type == "xtable" && isTRUE(include_proportions)) {
          out <- merge(out, effsize, sort = FALSE, all = TRUE)
        } else {
          if (bf_type == "xtable") {
            prefix <- "Cramers_"
          } else {
            prefix <- "d_"
          }
          ci_cols <- startsWith(colnames(effsize), "CI_")
          colnames(effsize)[ci_cols] <- paste0(prefix, colnames(effsize)[ci_cols])
          out$CI <- NULL
          out <- cbind(out, effsize)
        }
      },
      error = function(e) {
        NULL
      }
    )
  }

  # # Remove unnecessary columns
  # if ("CI" %in% names(out) && length(stats::na.omit(unique(out$CI))) == 1) {
  #   out$CI <- NULL
  # }
  if ("ROPE_CI" %in% names(out) && length(stats::na.omit(unique(out$ROPE_CI))) == 1) {
    out$ROPE_CI <- NULL
  }
  if ("ROPE_low" %in% names(out)) {
    out$ROPE_low <- NULL
    out$ROPE_high <- NULL
  }

  # ==== remove Component column if not needed

  if (!is.null(out$Component) && insight::n_unique(out$Component) == 1) out$Component <- NULL
  if (!is.null(out$Effects) && insight::n_unique(out$Effects) == 1) out$Effects <- NULL


  # ==== remove rows and columns with complete `NA`s

  out <- datawizard::remove_empty(out)

  # validation check: make sure BF column still exists,
  # see https://github.com/easystats/correlation/issues/269
  if (is.null(out$BF)) {
    out$BF <- NA
  }


  # ==== pretty parameter names

  cp <- out$Parameter

  if (!is.null(cleaned_params) && length(cleaned_params$Cleaned_Parameter) == length(cp) && bf_type == "linear") {
    match_params <- stats::na.omit(match(cp, cleaned_params$Parameter))
    cp <- cleaned_params$Cleaned_Parameter[match_params]
  }

  pretty_names <- stats::setNames(
    gsub("Cohens_d", "Cohen's D", gsub("Cramers_v", "Cramer's V", cp, fixed = TRUE), fixed = TRUE),
    out$Parameter
  )

  if (!"Method" %in% names(out)) {
    out$Method <- .method_BFBayesFactor(model)
  }

  # reorder
  col_order <- c(
    "Parameter", "Mean", "Median", "MAD",
    "CI", "CI_low", "CI_high", "SD", "Cohens_d", "Cramers_v", "Cramers_v_adjusted", "d_CI_low", "d_CI_high",
    "Cramers_CI_low", "Cramers_CI_high", "pd", "ROPE_Percentage", "Prior_Distribution",
    "Prior_Location", "Prior_Scale", "Effects", "Component", "BF", "Method"
  )
  out <- out[col_order[col_order %in% names(out)]]


  attr(out, "title") <- unique(out$Method)
  attr(out, "object_name") <- insight::safe_deparse_symbol(substitute(model))
  attr(out, "pretty_names") <- pretty_names
  attr(out, "ci_test") <- ci

  out <- .add_model_parameters_attributes(
    params = out,
    model = model,
    ci = ci,
    ci_method = ci_method,
    verbose = verbose
  )

  class(out) <- c("parameters_model", "see_parameters_model", class(out))
  out
}


#' @export
p_value.BFBayesFactor <- function(model, ...) {
  p <- bayestestR::p_direction(model)
  .data_frame(
    Parameter = .remove_backticks_from_string(p$Parameter),
    p = sapply(p$pd, bayestestR::convert_pd_to_p, simplify = TRUE)
  )
}


# helper -------


.classify_BFBayesFactor <- function(x) {
  insight::check_if_installed("BayesFactor")

  if (inherits(x@denominator, "BFcorrelation")) {
    "correlation"
  } else if (inherits(x@denominator, "BFoneSample")) {
    "ttest1"
  } else if (inherits(x@denominator, "BFindepSample")) {
    "ttest2"
  } else if (inherits(x@denominator, "BFmetat")) {
    "meta"
  } else if (inherits(x@denominator, "BFlinearModel")) {
    "linear"
  } else if (inherits(x@denominator, "BFcontingencyTable")) {
    "xtable"
  } else if (inherits(x@denominator, "BFproportion")) {
    "proptest"
  } else {
    class(x@denominator)
  }
}

.method_BFBayesFactor <- function(x) {
  if (inherits(x@denominator, "BFcorrelation")) {
    "Bayesian correlation analysis"
  } else if (inherits(x@denominator, c("BFoneSample", "BFindepSample"))) {
    "Bayesian t-test"
  } else if (inherits(x@denominator, "BFmetat")) {
    "Meta-analytic Bayes factors"
  } else if (inherits(x@denominator, "BFlinearModel")) {
    "Bayes factors for linear models"
  } else if (inherits(x@denominator, "BFcontingencyTable")) {
    "Bayesian contingency table analysis"
  } else if (inherits(x@denominator, "BFproportion")) {
    "Bayesian proportion test"
  } else {
    NA_character_
  }
}