After running a statistical model in R (e.g., glm, lm, lme4::lmer, etc.), I run the summary() command with corr=TRUE to get the Correlation of Coefficients table. It features a matrix of correlations for the intercept and the independent variables in the given model. What I would like to do is extract the columns that make those correlations possible. For instance, if the model is x ~ a + b, and the table looks like this...
(Intercept) a
a 0.##
b 0.## 0.##
I want to extract the columns that allow for the correlation between a and b.
I have found various commands to extract fitted values and residuals, but nothing to yet that would give me values for a and b that correspond to their correlations in that table.
What you want is the
summary(.)$correlation.If you want to extract something from an
object, look into the structurestr(object)to find the desired element. (If you are working in RStudio, perhaps start withstr(object, max.levels=1)as it tends to hang up or crash if the output is too large.)Looking into the source code of
fitted()methods such asstats:::fitted.lmreveals, that they essentially extract the$fitted.valueselement of the respective object (similar applies toresid()).Same way we could write a function
ex_corr_lm(). To obtain the RHS variables automatically we may useall.vars()on the formula element.The
objectalso contains themodeldata which is the part of data from the original data used to fit the model. If there wereNAs, they might be removed. We can use it to reconstruct the columns that "make those correlations possible".If we set
data=TRUE, we can obtain the respective columns.ex_corr_lm()throws a list with correlations and data columns in this case.We can use
cor()on them. Note, that correlations of the estimated coefficients and the correlation between the variables themselves aren't necessarily the same.Data: