| compare_levels {tidybayes} | R Documentation |
Compare the value of draws of some variable from a Bayesian model for different levels of a factor
Description
Given posterior draws from a Bayesian model in long format (e.g. as
returned by spread_draws()), compare the value of a variable in those draws
across different paired combinations of levels of a factor.
Usage
compare_levels(
data,
variable,
by,
fun = `-`,
comparison = "default",
draw_indices = c(".chain", ".iteration", ".draw"),
ignore_groups = ".row"
)
Arguments
data |
Long-format |
variable |
Bare (unquoted) name of a column in data representing the
variable to compare across levels. Can be a numeric variable (as in
long-data-frame-of-draws format) or a |
by |
Bare (unquoted) name of a column in data that is a
|
fun |
Binary function to use for comparison. For each pair of levels of
|
comparison |
One of (a) the comparison types |
draw_indices |
Character vector of column names in |
ignore_groups |
character vector of names of groups to ignore by
default in the input grouping. This is primarily provided to make it
easier to pipe output of |
Details
This function simplifies conducting comparisons across levels of some
variable in a tidy data frame of draws. It applies fun to all
values of variable for each pair of levels of by as selected
by comparison. By default, all pairwise comparisons are generated if
by is an unordered factor and ordered comparisons are made if
by is ordered.
The included comparison types are:
-
ordered: compare each leveliwith leveli - 1; e.g.fun(i, i - 1) -
pairwise: compare each level ofbywith every other level. -
control: compare each level ofbywith the first level ofby. If you wish to compare with a different level, you can first applyrelevel()tobyto set the control (reference) level. -
default: useorderedifis.ordered(by)andpairwiseotherwise.
Value
A data.frame with the same columns as data, except
that the by column contains a symbolic representation of the
comparison of pairs of levels of by in data, and
variable contains the result of that comparison.
Author(s)
Matthew Kay
See Also
emmeans_comparison() to use emmeans-style contrast methods with
compare_levels().
Examples
library(dplyr)
library(ggplot2)
data(RankCorr, package = "ggdist")
# Let's do all pairwise comparisons of b[i,1]:
RankCorr %>%
spread_draws(b[i,j]) %>%
filter(j == 1) %>%
compare_levels(b, by = i) %>%
median_qi()
# Or let's plot all comparisons against the first level (control):
RankCorr %>%
spread_draws(b[i,j]) %>%
filter(j == 1) %>%
compare_levels(b, by = i, comparison = control) %>%
ggplot(aes(x = b, y = i)) +
stat_halfeye()
# Or let's plot comparisons of all levels of j within
# all levels of i
RankCorr %>%
spread_draws(b[i,j]) %>%
group_by(i) %>%
compare_levels(b, by = j) %>%
ggplot(aes(x = b, y = j)) +
stat_halfeye() +
facet_grid(cols = vars(i))