Skip to content

Add tidiers for margins and mfx objects #700

@grantmcdermott

Description

@grantmcdermott

It would be great to have tidy methods for objects from the margins and mfx packages.

Among other things, this would go a long way towards improving the table support for generalized linear models like logit and probit regressions, where you often want to report actual marginal effects rather than the naive coefficient values. (I'm thinking of the fact that modern table-exporting packages like huxtable and gtsummary rely on broom::tidy() as a first step.) AFAIK, there is currently no fully automated way to produce, say, a LaTeX table of marginal effects from a logistic regression in R.

A potential point of convenience here is that margins and mfx both produce output that already closely resemble tidied regression output.

## Run a logistic regression
log_reg <- glm(am ~ cyl + hp + wt, data = mtcars, family = binomial)

## Tidy (but naive) coefficient values
library(broom)
tidy(log_reg)
#> # A tibble: 4 x 5
#>   term        estimate std.error statistic p.value
#>   <chr>          <dbl>     <dbl>     <dbl>   <dbl>
#> 1 (Intercept)  19.7       8.12       2.43   0.0152
#> 2 cyl           0.488     1.07       0.455  0.649 
#> 3 hp            0.0326    0.0189     1.73   0.0840
#> 4 wt           -9.15      4.15      -2.20   0.0276

## Get the actual marginal effects instead

## Option 1: margins package
library(margins, quietly = T)
summary(margins(log_reg))
#>  factor     AME     SE       z      p   lower   upper
#>     cyl  0.0215 0.0470  0.4567 0.6479 -0.0706  0.1135
#>      hp  0.0014 0.0006  2.3197 0.0204  0.0002  0.0026
#>      wt -0.4025 0.1154 -3.4880 0.0005 -0.6287 -0.1764

## Option 2: mfx package
library(mfx, quietly = T, warn.conflicts = F)
logitmfx(log_reg, atmean = F, data = mtcars)
#> Call:
#> logitmfx(formula = log_reg, data = mtcars, atmean = F)
#> 
#> Marginal Effects:
#>          dF/dx  Std. Err.       z  P>|z|
#> cyl  0.0214528  0.0499376  0.4296 0.6675
#> hp   0.0014339  0.0014602  0.9820 0.3261
#> wt  -0.4025475  0.3782646 -1.0642 0.2872

Created on 2019-05-02 by the reprex package (v0.2.1)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions