Convert emmeans contrast methods into comparison functions suitable for use with compare_levels().

emmeans_comparison(method, ...)

Arguments

method

An emmeans-style contrast method. One of: (1) a string specifying the name of an emmeans contrast method, like "pairwise", "trt.vs.ctrl", "eff"; or (2) an emmeans-style contrast function itself, like emmeans::pairwise.emmc, emmeans::trt.vs.ctrl.emmc, etc, or a custom function that takes a vector of factor levels and returns a contrast matrix.

...

Arguments passed on to the contrast method.

Value

A function that takes a single argument, var, containing a variable to generate contrasts for (e.g., a factor or a character vector) and returns a function that generates a list of named unevaluated expressions representing different contrasts of that variable. This function is suitable to be used as the comparison argument in compare_levels().

Details

Given an emmeans contrast method name as a string (e.g., "pairwise", "trt.vs.ctrl", etc) or an emmeans-style contrast function (e.g., emmeans::pairwise.emmc, emmeans::trt.vs.ctrl.emmc, etc), emmeans_comparison() returns a new function that can be used in the comparison argument to compare_levels() to compute those contrasts.

See also

compare_levels(), emmeans::contrast-methods. See gather_emmeans_draws() for a different approach to using emmeans with tidybayes.

Author

Matthew Kay

Examples

if (requireNamespace("emmeans", quietly = TRUE)) { library(dplyr) library(ggplot2) data(RankCorr, package = "ggdist") # emmeans contrast methods return matrices. E.g. the "eff" comparison # compares each level to the average of all levels: print(emmeans:::eff.emmc(c("a","b","c","d"))) # tidybayes::compare_levels() can't use a contrast matrix like this # directly; it takes arbitrary expressions of factor levels. But # we can use `emmeans_comparison` to generate the equivalent expressions: print(emmeans_comparison("eff")(c("a","b","c","d"))) # We can use the "eff" comparison type with `compare_levels()` as follows: RankCorr %>% spread_draws(b[i,j]) %>% filter(j == 1) %>% compare_levels(b, by = i, comparison = emmeans_comparison("eff")) %>% median_qi() }
#> a effect b effect c effect d effect #> a 0.75 -0.25 -0.25 -0.25 #> b -0.25 0.75 -0.25 -0.25 #> c -0.25 -0.25 0.75 -0.25 #> d -0.25 -0.25 -0.25 0.75 #> $`a effect` #> 0.75 * a + -0.25 * b + -0.25 * c + -0.25 * d #> #> $`b effect` #> -0.25 * a + 0.75 * b + -0.25 * c + -0.25 * d #> #> $`c effect` #> -0.25 * a + -0.25 * b + 0.75 * c + -0.25 * d #> #> $`d effect` #> -0.25 * a + -0.25 * b + -0.25 * c + 0.75 * d #>
#> # A tibble: 3 x 8 #> i j b .lower .upper .width .point .interval #> <chr> <int> <dbl> <dbl> <dbl> <dbl> <chr> <chr> #> 1 1 effect 1 -0.361 -0.546 -0.168 0.95 median qi #> 2 2 effect 1 -0.0209 -0.243 0.208 0.95 median qi #> 3 3 effect 1 0.376 0.159 0.598 0.95 median qi