I need to test the difference between two coefficients (I have two different regressions), how I did:
car<- mtcars
first<- lm(formula = vs ~ gear + carb,
data = car)
second<- lm(formula = vs ~ gear + disp,
data = car)
coef_diff <- coef(first)["gear"] - coef(second)["gear"]
t.test(coef(first)["gear"], coef(second)["gear"],choice= "two.side",var.equal= TRUE)
The message I receveid:
Error in t.test.default(coef(first)["gear"], coef(second)["gear"], choice = "two.side", :
number insufficient of observations
You could use the linearHypothesis
function from the car
package, which can test whether two coefficients in the same model are equal.
third <- lm(formula = vs ~ gear + carb + disp, data = car)
car::linearHypothesis(third, "carb = disp")
Linear hypothesis test
Hypothesis:
carb - disp = 0
Model 1: restricted model
Model 2: vs ~ gear + carb + disp
Res.Df RSS Df Sum of Sq F Pr(>F)
1 29 3.4685
2 28 3.1136 1 0.35489 3.1914 0.08486 .