# Introduction to ‘bayesMeanScale’

This vignette provides an overview of the `bayesMeanScale` package, which is designed to compute model predictions, marginal effects, and comparisons of marginal effects for several different fixed-effect generalized linear models fit using the `rstanarm` package (https://mc-stan.org/rstanarm/). In particular, these statistics are computed on the mean scale rather than the link scale for easier interpretation. For example, rather than working on the log-odds scale for a logistic regression, we focus on the probability scale.

To get to the mean scale, `bayesMeanScale` takes a random sample with replacement from the joint posterior distribution. Then, this matrix is multiplied by the adjusted data matrix (adjusted according to your values of interest). Finally, the inverse link function is applied to transform the predictions to the mean scale.

Predictions are computed by holding one or more explanatory variables fixed at particular values and either averaging over the rows of the data (average marginal predictions) or holding all other covariates at their means (marginal predictions at the mean). Marginal effects can also be calculated by averaging over the data (average marginal effect) or holding covariates at their means (marginal effect at the mean).

The third workhorse function of the package compares marginal effects against each other. This is particularly useful for testing non-linear interaction effects such as those that appear in generalized linear models that do not use the identity link.

## Predictions

### Average marginal predictions

The examples below use the `wells` data from the `rstanarm` package. Use `?rstanarm::wells` to view the documentation on this dataset.

For average marginal predictions, the goal is to get predictions at important settings of one or more of the model explanatory variables. These predictions are then averaged over the rows of the data.

    if(!all(sapply(c('bayesMeanScale', 'rstanarm', 'flextable', 'magrittr', 'MASS'), function(x) require(x, character.only=T, quietly=T)))){
      knitr::opts_chunk$set(eval=F)
    } else{
        sapply(c('bayesMeanScale', 'rstanarm', 'flextable', 'magrittr', 'MASS'), function(x) library(x, character.only=T, quietly=T))
    }

    # Simulate the data #

    modelData       <- rstanarm::wells
    modelData$assoc <- ifelse(modelData$assoc==1, 'Y', 'N')

    binomialModel <- stan_glm(switch ~ dist*educ + arsenic + I(arsenic^2) + assoc,
                              data    = modelData,
                              family  = binomial,
                              refresh = 0)

    bayesPredsF(binomialModel,
                at = list(arsenic = c(.82, 1.3, 2.2)))

    ##  arsenic   mean  lower  upper
    ##     0.82 0.4707 0.4483 0.4947
    ##     1.30 0.5518 0.5317 0.5682
    ##     2.20 0.6715 0.6505 0.6972

The output contains the unique values for the “at” variable(s), the posterior means, and the lower and upper bounds of the credible intervals.

### Marginal predictions at the mean

For marginal predictions at the mean, the goal is essentially the same except that we want to hold the covariates at their means. In the example below, all explanatory variables except for “arsenic” are held at their means for the computation. Since “assoc” is a discrete variable, we hold it at the proportion of cases that equaled “Y”.

    bayesPredsF(binomialModel,
                at       = list(arsenic = c(.82, 1.3, 2.2)),
                at_means = TRUE)

    ##  arsenic   mean  lower  upper
    ##     0.82 0.4669 0.4416 0.4898
    ##     1.30 0.5514 0.5336 0.5722
    ##     2.20 0.6764 0.6525 0.7011

The results are slightly different than the average marginal predictions. From a computational standpoint, setting “at_means” to “TRUE” makes for a substantially faster computation. For relatively small models, this speed advantage is likely trivial, but it can make a noticeable difference when working with big data models.

### Average marginal predictions for count probabilities

You can also get the predictions for the count probabilities from a Poisson or negative binomial model. Here, rather than looking at the rate, or mean, parameter, we investigate the probabilities of particular counts. This is an effective approach for summarizing count models in more depth.

    crabs <- read.table("https://stat4ds.rwth-aachen.de/data/Crabs.dat", header=T)

    poissonModel  <- stan_glm(sat ~ weight + width,
                              data    = crabs,
                              family  = poisson,
                              refresh = 0)

    bayesCountPredsF(poissonModel,
                     counts = c(0,1,2),
                     at     = list(weight=c(2,3,4)))

    ##  weight count   mean  lower  upper
    ##       2     0 0.1087 0.0749 0.1471
    ##       3     0 0.0336 0.0130 0.0575
    ##       4     0 0.0090 0.0000 0.0333
    ##       2     1 0.2353 0.1905 0.2847
    ##       3     1 0.1085 0.0603 0.1584
    ##       4     1 0.0350 0.0003 0.1046
    ##       2     2 0.2597 0.2388 0.2706
    ##       3     2 0.1809 0.1363 0.2205
    ##       4     2 0.0745 0.0028 0.1709

## Marginal effects

### Average marginal effects

The concept of average marginal effects is straightforward. For discrete changes, we simply take two posterior distributions of average marginal predictions and subtract one from the other. In the example below, we see that the average expected probability of switching wells for families that had an arsenic level of 2.2 is roughly 27 percentage points greater than for a family that had an arsenic level of .82.

    binomialAME <- bayesMargEffF(binomialModel,
                                 marginal_effect = 'arsenic',
                                 start_value     = 2.2,
                                 end_value       = .82)

    binomialAME

    ##  marg_effect start_val end_val  mean  lower  upper
    ##      arsenic       2.2    0.82 0.267 0.2153 0.3112

    head(binomialAME$diffDraws)

    ##         diff   comparison marg_effect
    ##        <num>       <char>      <char>
    ## 1: 0.2637691 2.2 vs. 0.82     arsenic
    ## 2: 0.1945902 2.2 vs. 0.82     arsenic
    ## 3: 0.2595263 2.2 vs. 0.82     arsenic
    ## 4: 0.2346781 2.2 vs. 0.82     arsenic
    ## 5: 0.2496308 2.2 vs. 0.82     arsenic
    ## 6: 0.2744235 2.2 vs. 0.82     arsenic

Also note that we can access the posterior distribution of the marginal effects. This can be useful for graphing purposes and to describe the marginal effect distributions in more detail.

As an alternative to computing some discrete change in arsenic, we can approximate the average instantaneous rate of change by supplying “instantaneous” as our value for the “start_value” and “end_value” arguments.

    binomialAMEInstant <- bayesMargEffF(binomialModel,
                                        marginal_effect = 'arsenic',
                                        start_value     = 'instantaneous',
                                        end_value       = 'instantaneous')

    binomialAMEInstant

    ##  marg_effect     start_val       end_val   mean  lower  upper
    ##      arsenic instantaneous instantaneous 0.1993 0.1503 0.2423

We can also compute multiple marginal effects. When doing so, it is necessary to specify the start and end values in a list.

    bayesMargEffF(binomialModel,
                  marginal_effect = c('arsenic', 'dist'),
                  start_value     = list(2.2, 64.041),
                  end_value       = list(.82, 21.117))

    ##  marg_effect start_val end_val    mean   lower   upper
    ##      arsenic     2.200   0.820  0.2678  0.2153  0.3143
    ##         dist    64.041  21.117 -0.0964 -0.1156 -0.0781

The “at” argument allows the user to specify particular values for one or more covariates, and they must be specified in a list. The example below specifies at values for “educ” given that we have an interaction between “dist” and “educ” in the model. If there is an interaction effect on the mean (probability) scale, we would expect the marginal effect of “dist” to be different at various levels of “educ.” The final section will cover how to test these marginal effects against each other.

    binomialAMEInteraction <- bayesMargEffF(binomialModel,
                                            marginal_effect = 'dist',
                                            start_value     = 'instantaneous',
                                            end_value       = 'instantaneous',
                                            at              = list(educ=c(0, 5, 8)))

    binomialAMEInteraction

    ##  educ marg_effect     start_val       end_val    mean   lower   upper
    ##     0        dist instantaneous instantaneous -0.0033 -0.0039 -0.0026
    ##     5        dist instantaneous instantaneous -0.0022 -0.0026 -0.0018
    ##     8        dist instantaneous instantaneous -0.0015 -0.0021 -0.0010

### Average marginal effects for count probabilities

You can also get the marginal effects for the count probabilities from a Poisson or negative binomial model.

    countMarg <- bayesCountMargEffF(poissonModel,
                                    counts          = c(0,1,2),
                                    marginal_effect = 'width',
                                    start_value     = 25,
                                    end_value       = 20,
                                    at              = list(weight=c(2,3,4)))

    countMarg

    ##  weight count marg_effect start_val end_val    mean   lower  upper
    ##       2     0       width        25      20 -0.0712 -0.2202 0.0555
    ##       3     0       width        25      20 -0.0519 -0.1734 0.0124
    ##       4     0       width        25      20 -0.0314 -0.1428 0.0011
    ##       2     1       width        25      20 -0.0490 -0.1266 0.0453
    ##       3     1       width        25      20 -0.0661 -0.1507 0.0319
    ##       4     1       width        25      20 -0.0553 -0.1673 0.0035
    ##       2     2       width        25      20  0.0165 -0.0121 0.0639
    ##       3     2       width        25      20 -0.0229 -0.0677 0.0556
    ##       4     2       width        25      20 -0.0486 -0.1140 0.0102

### Marginal effects at the mean

Marginal effects at the mean compute the differences while holding the covariates at their means. Like the marginal predictions at the mean, specifying “at_means=TRUE” allows for a much faster computation than specifying “at_means=FALSE”.

    binomialMEMInteraction <- bayesMargEffF(binomialModel,
                                            marginal_effect = 'dist',
                                            start_value     = 64.041,
                                            end_value       = 21.117,
                                            at              = list(educ=c(0, 5, 8)),
                                            at_means        = TRUE)

    binomialMEMInteraction

    ##  educ marg_effect start_val end_val    mean   lower   upper
    ##     0        dist    64.041  21.117 -0.1528 -0.1867 -0.1178
    ##     5        dist    64.041  21.117 -0.1000 -0.1212 -0.0783
    ##     8        dist    64.041  21.117 -0.0688 -0.0940 -0.0460

## Comparing marginal effects

After computing multiple marginal effects for a model, you might like to compare them against one another. The “bayesMargCompareF” function calculates tests for the pairs of marginal effects that you computed with “bayesMargEffF”. In the example below, we are able to investigate the interaction effect between “dist” and “educ”. We see that the marginal effect of “dist” is meaningfully different at different levels of “educ”.

    bayesMargCompareF(binomialAMEInteraction)

    ##  educ1 educ2                         marg_effect   mean lower  upper
    ##      5     0 dist (Instantaneous rate of change) 0.0011 6e-04 0.0016
    ##      8     0 dist (Instantaneous rate of change) 0.0018 9e-04 0.0026
    ##      8     5 dist (Instantaneous rate of change) 0.0007 4e-04 0.0010

You can also compare the marginal effects on count probabilities, shown in the example below.

    bayesMargCompareF(countMarg)

    ##  weight1 weight2 count       marg_effect    mean   lower  upper
    ##        3       2     0 width (25 vs. 20)  0.0193 -0.0281 0.0479
    ##        4       2     0 width (25 vs. 20)  0.0398 -0.0392 0.0973
    ##        4       3     0 width (25 vs. 20)  0.0205 -0.0098 0.0456
    ##        3       2     1 width (25 vs. 20) -0.0171 -0.0506 0.0045
    ##        4       2     1 width (25 vs. 20) -0.0063 -0.0723 0.0337
    ##        4       3     1 width (25 vs. 20)  0.0107 -0.0312 0.0414
    ##        3       2     2 width (25 vs. 20) -0.0394 -0.0867 0.0324
    ##        4       2     2 width (25 vs. 20) -0.0651 -0.1471 0.0053
    ##        4       3     2 width (25 vs. 20) -0.0257 -0.0752 0.0164

## Proportional odds models

The examples below use the `housing` data from the `MASS` package. Use `?MASS::housing` to view the documentation on this dataset.

We can also compute predictions, marginal effects, and comparisons of marginal effects for proportional odds models. Posterior means and credible intervals are computed with respect to each outcome of the response variable.

    propOddsModel <- stan_polr(Sat ~ Infl + Type,
                               data    = housing,
                               prior   = rstanarm::R2(0.2, 'mean'),
                               refresh = 0)

    bayesOrdinalPredsF(propOddsModel,
                       at = list(Type=c("Tower", "Apartment")))

    ##       Type outcome   mean  lower  upper
    ##      Tower     Low 0.3408 0.2552 0.4384
    ##  Apartment     Low 0.3429 0.1714 0.5474
    ##      Tower  Medium 0.3221 0.3058 0.3406
    ##  Apartment  Medium 0.3122 0.2733 0.3410
    ##      Tower    High 0.3371 0.2447 0.4271
    ##  Apartment    High 0.3449 0.1709 0.5468

    propOddsMarg <- bayesOrdinalMargEffF(propOddsModel,
                                         marginal_effect = "Infl",
                                         start_value     = "Low",
                                         end_value       = "High",
                                         at              = list(Type=c("Tower", "Apartment")))

    propOddsMarg

    ##  outcome      Type marg_effect start_val end_val    mean   lower  upper
    ##      Low     Tower        Infl       Low    High -0.0043 -0.1506 0.1517
    ##      Low Apartment        Infl       Low    High -0.0039 -0.1518 0.1564
    ##   Medium     Tower        Infl       Low    High  0.0086 -0.0012 0.0344
    ##   Medium Apartment        Infl       Low    High  0.0077 -0.0249 0.0555
    ##     High     Tower        Infl       Low    High -0.0043 -0.1703 0.1423
    ##     High Apartment        Infl       Low    High -0.0038 -0.1606 0.1453

    bayesMargCompareF(propOddsMarg)

    ##      Type1 Type2 outcome         marg_effect   mean   lower  upper
    ##  Apartment Tower     Low Infl (Low vs. High)  5e-04 -0.0194 0.0217
    ##  Apartment Tower  Medium Infl (Low vs. High) -9e-04 -0.0346 0.0381
    ##  Apartment Tower    High Infl (Low vs. High)  5e-04 -0.0168 0.0239

## List of models currently supported

Class | Family | Links
--- | --- | ---
stanreg | beta | logit; probit; cloglog
stanreg | binomial | logit; probit; cloglog
stanreg | Gamma | inverse; log; identity
stanreg | gaussian | identity
stanreg | neg_binomial_2 | identity; log; sqrt
stanreg | poisson | identity; log; sqrt
stanreg; polr | binomial | logit; probit; cloglog

## References

Agresti, Alan. 2013. Categorical Data Analysis. Third Edition. New York: Wiley

Long, J. Scott and Jeremy Freese. 2001. “Predicted Probabilities for Count Models.” Stata Journal 1(1): 51-57.

Long, J. Scott and Sarah A. Mustillo. 2018. “Using Predictions and Marginal Effects to Compare Groups in Regression Models for Binary Outcomes.” Sociological Methods & Research 50(3): 1284-1320.

Mize, Trenton D. 2019. “Best Practices for Estimating, Interpreting, and Presenting Non-linear Interaction Effects.” Sociological Science 6: 81-117.