margins icon indicating copy to clipboard operation
margins copied to clipboard

Bug in cplot

Open giuseppec opened this issue 7 years ago • 2 comments

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")

giuseppec avatar May 10 '17 14:05 giuseppec

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 avatar Jan 25 '18 20:01 leeper

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

leeper avatar Feb 08 '18 21:02 leeper