Error in running the "margins" function in R

640 Views Asked by At

I have built a simple lm model as shown below:

model1 = lm(score ~
   study_hours +
   courses_taken +
   study_hours:courses_taken +
   taken_before +
   mediumenjoyment +
   highenjoyment +
   female,
   data = course_data)

now, I'm trying to compute the marginal effect at the means. So, my code for doing so is:

mean_list = data.frame(mean(score),
                       mean(study_hours),
                       mean(courses_taken),
                       mean(study_hours:courses_taken),
                       mean(taken_before),
                       mean(mediumenjoyment),
                       mean(highenjoyment),
                       mean(female))


mar2 = margins(model1, data = mean_list)

summary(mar2)

But when I run the code, this error is raised:

Error in mean(score) : object 'score' not found
1

There are 1 best solutions below

0
On

I suspect that the error is in this line:

mean(study_hours:courses_taken)

Typically, object names in R do not include colons, so I imagine that you can’t take the mean.

In passing, I’ll note that the margins package works great in many cases, but that it is not actively being developed. You could try the newer marginaleffects package (disclaimer: I am the author). That package allows you to compute marginal effects at the mean (documentation) easily by typing:

library(marginaleffects)
mod <- lm(mpg ~ ., data = mtcars)
mfx <- marginaleffects(mod, newdata = datagrid())
summary(mfx)
#> Average marginal effects 
#>    Term   Effect Std. Error z value Pr(>|z|)    2.5 %   97.5 %
#> 1   cyl -0.11144    1.04502 -0.1066 0.915075 -2.15964  1.93676
#> 2  disp  0.01334    0.01786  0.7468 0.455209 -0.02166  0.04834
#> 3    hp -0.02148    0.02177 -0.9868 0.323717 -0.06415  0.02118
#> 4  drat  0.78711    1.63537  0.4813 0.630301 -2.41816  3.99238
#> 5    wt -3.71530    1.89441 -1.9612 0.049857 -7.42829 -0.00232
#> 6  qsec  0.82104    0.73083  1.1234 0.261255 -0.61137  2.25345
#> 7    vs  0.31776    2.10451  0.1510 0.879982 -3.80700  4.44252
#> 8    am  2.52023    2.05665  1.2254 0.220423 -1.51073  6.55119
#> 9  gear  0.65541    1.49326  0.4389 0.660724 -2.27132  3.58215
#> 10 carb -0.19942    0.82875 -0.2406 0.809845 -1.82374  1.42491
#> 
#> Model type:  lm 
#> Prediction type:  response