Learn R Programming

tidybayes (version 0.12.1.9000)

gather_emmeans_samples: Extract tidy samples of estimated marginal means (emmeans/lsmeans) from a Bayesian model fit

Description

Extract samples from the result of a call to emmeans (formerly lsmeans) or ref_grid applied to a Bayesian model.

Usage

gather_emmeans_samples(object)

Arguments

object

An emmGrid object such as returned by ref_grid or emmeans.

Value

A data frame of tidy samples. The columns of the reference grid are returned as-is, with an additional column called estimate containing samples from the marginal estimates (the name estimate is used for compatibility with gather_samples and tidy). The resulting data frame is grouped by the columns from the reference grid to make use of summary functions like point_interval straightforward.

Details

emmeans provides a convenient syntax for generating marginal estimates from a model, and can be applied to various Bayesian models, like stanreg-objects and MCMCglmm. Given a ref_grid object as returned by functions like ref_grid or emmeans applied to a Bayesian model, gather_emmeans_samples returns a tidy format data frame of samples from the marginal posterior distributions generated by emmeans.

See Also

emmeans

Examples

Run this code
# NOT RUN {
library(dplyr)
library(magrittr)
library(rstanarm)
library(emmeans)

# Here's an example dataset with a categorical predictor (`condition`) with several levels:
set.seed(5)
n = 10
n_condition = 5
ABC =
  data_frame(
    condition = rep(c("A","B","C","D","E"), n),
    response = rnorm(n * 5, c(0,1,2,1,-1), 0.5)
  )

m = stan_glm(response ~ condition, data = ABC,
  # 1 chain / few iterations just so example runs quickly
  # do not use in practice
  chains = 1, iter = 500)

# Once we've fit the model, we can use emmeans() (and functions
# from that package) to get whatever marginal estimates we want.
# For example, we can get estimated marginal means by condition:
m %>%
  emmeans(~ condition) %>%
  gather_emmeans_samples() %>%
  median_qi()

# or we could get pairwise differences:
m %>%
  emmeans( ~ condition) %>%
  contrast(method = "pairwise") %>%
  gather_emmeans_samples() %>%
  median_qi()

# see the documentation of emmeans() for more examples of types of
# contrasts supported by that packge.

# }

Run the code above in your browser using DataLab