margins icon indicating copy to clipboard operation
margins copied to clipboard

Rows and columns order in a matrix returned by vcov(margins_object)

Open tzoltak opened this issue 5 years ago • 0 comments

[x] a possible bug

This is not a very serious problem, however it is on the one hand inconvenient and on the other hand a little trouble-prone for careless users: if there are predictors in a model, that are factors, rows and columns in a matrix returned by vcov(margins_object) have different order than what summary(margins_object) returns.

This makes hard to use vcov(margins_object) - while calling vcov() is widespread method of getting coefficients variances - and if someone is not aware about this happens, he may end up using wrong variances/covariances with respect to given AMEs.

## load package
library("margins")
require("datasets")

## code goes here
x <- lm(mpg ~ wt + factor(cyl) * hp, data = mtcars)
mrg = margins(x)
vcov(mrg)
summary(mrg)$AME
cbind(vcov_rownames = sub("dydx_(.*)\\.1", "\\1", rownames(vcov(mrg))),
         AMEs_names = names(summary(mrg)$AME))

## session info for your system
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 18363)

Matrix products: default

locale:
[1] LC_COLLATE=Polish_Poland.1250  LC_CTYPE=Polish_Poland.1250   
[3] LC_MONETARY=Polish_Poland.1250 LC_NUMERIC=C                  
[5] LC_TIME=Polish_Poland.1250    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] margins_0.3.25

loaded via a namespace (and not attached):
[1] MASS_7.3-51.4     compiler_3.6.1    tools_3.6.1       data.table_1.12.8
[5] prediction_0.3.14

It seems appealing to do something with this is about line 39 in build_margins.R - if variables object could get the proper order in that place, everything afterwards should preserve this order. However I'm not sure from where to get a proper order of terms - perhaps find_terms_in_model() should be modified so it would include this order in an object it returns?

tzoltak avatar Dec 22 '19 20:12 tzoltak