research111 research111 - 2 months ago 14
R Question

Error when using `delthamethod`{msm} for a fitted linear model: covariances should be a n x n matrix

I am using the

from package
to derive the standard error of a transformed variable.

Example code:


x1 <- 1:10
x2 <- c(0,0,0,0,0,0,0,0,0,0)
y <- c(1,3,3,4,5,7,7,8,9,10)

m1 <- lm(y~x1+x2)

deltamethod(~ (1-x1), coef(m1), vcov(m1))

The error I get is "Covariances should be a 3x3 matrix". The reason is that 1 variable does not have any variation (x2 is always zero) and has "NA" in the regression output.

Is there an easy fix to this? I know I could leave the variable out, but I am running more than 1.000 regressions with each around 15 parameters to estimate, and the NA variables (without variation) are every time different variables.


How about:

deltamethod(~(1-x1), na.omit(coef(m1)), vcov(m1))
# [1] 0.2949063