leeper / margins

An R Port of Stata's 'margins' Command
https://cloud.r-project.org/package=margins
Other
262 stars 40 forks source link

Bug in cplot #64

Open giuseppec opened 7 years ago

giuseppec commented 7 years ago
library(datasets)
library(margins)
mtcars$cyl = as.factor(mtcars$cyl)
mod = lm(mpg ~ cyl + hp + (cyl + hp):carb, data = mtcars)

ame.effects = summary(margins(mod))$AME
ame.effects

# Your plots seem to have a bug as the slope is not always the same as the slope of the ame (which, however, should be the case, right?)
cplot(mod, x = "carb")
abline(a = mean(mtcars$mpg), # use anything as intercept
  b = ame.effects["carb"], col = "red")

# here the slope is equivalent to the ame value as the slope of the green and red curves are the same
library("pdp")
pdp = partial(mod, pred.var = "carb", grid.resolution = nrow(mtcars))
lines(pdp$carb, pdp$yhat, col = "green")
leeper commented 6 years ago

This isn't exactly a bug but it's not the best behavior. The line is the predicted value holding all other variables at their mean or mode (MEMs), which differs from the behavior of margins() which calculates average marginal effects (AMEs). The AME in this example is -0.9258. The MEM is -2.219. Leaving this open but just wanted to note it is the (currently) intended behavior but probably not what the user actually wants.

leeper commented 6 years ago

This is trivial to fix, once variances of predictions are setup: https://github.com/leeper/prediction/issues/17