Skip to contents

Extract a reference grid from objects created by {emmeans} and {marginaleffects}

Usage

# S3 method for class 'emmGrid'
get_datagrid(x, ...)

Arguments

x

An object created by a function such as emmeans::emmeans(), marginaleffects::slopes(), etc.

...

Currently not used

Value

A data.frame with key columns that identify the rows in x.

Details

Note that for {emmeans} inputs the results is a proper grid (all combinations of values are represented), except when a nesting structure is detected. Additionally, when the input is an emm_list object, the function will rbind() the data-grids of all the elements in the input.

For {marginaleffects} inputs, the output may very well be a non-grid result. See examples.

Examples

data("mtcars")
mtcars$cyl <- factor(mtcars$cyl)

mod <- glm(am ~ cyl + hp + wt,
  family = binomial("logit"),
  data = mtcars
)

em1 <- emmeans::emmeans(mod, ~ cyl + hp, at = list(hp = c(100, 150)))
get_datagrid(em1)
#>   cyl  hp
#> 1   4 100
#> 2   6 100
#> 3   8 100
#> 4   4 150
#> 5   6 150
#> 6   8 150

contr1 <- emmeans::contrast(em1, method = "consec", by = "hp")
get_datagrid(contr1)
#>      contrast  hp
#> 1 cyl6 - cyl4 100
#> 2 cyl8 - cyl6 100
#> 3 cyl6 - cyl4 150
#> 4 cyl8 - cyl6 150

eml1 <- emmeans::emmeans(mod, pairwise ~ cyl | hp, at = list(hp = c(100, 150)))
get_datagrid(eml1) # not a "true" grid
#>     hp  cyl    contrast
#> 1  100    4        <NA>
#> 2  100    6        <NA>
#> 3  100    8        <NA>
#> 4  150    4        <NA>
#> 5  150    6        <NA>
#> 6  150    8        <NA>
#> 7  100 <NA> cyl4 - cyl6
#> 8  100 <NA> cyl4 - cyl8
#> 9  100 <NA> cyl6 - cyl8
#> 10 150 <NA> cyl4 - cyl6
#> 11 150 <NA> cyl4 - cyl8
#> 12 150 <NA> cyl6 - cyl8
if (FALSE) { # insight::check_if_installed("marginaleffects", quietly = TRUE, minimum_version = "0.24.0.6")
mfx1 <- marginaleffects::slopes(mod, variables = "hp")
get_datagrid(mfx1) # not a "true" grid

mfx2 <- marginaleffects::slopes(mod, variables = c("hp", "wt"), by = "am")
get_datagrid(mfx2)

contr2 <- marginaleffects::avg_comparisons(mod)
get_datagrid(contr2) # not a "true" grid
}