【问题标题】:R code to test the difference between coefficients of regressors from one regressionR代码来测试一个回归的回归系数之间的差异
【发布时间】:2016-06-12 13:05:42
【问题描述】:

我想测试一个线性回归中的系数是否彼此不同,或者其中至少一个是否与某个特定值显着不同,比如 0,这在 Stata 中似乎很直观。例如

webuse iris reg iris seplen sepwid petlen seplen==sepwid==petlen seplen==sepwid==petlen==0

如果我想在 R 中进行测试,我想知道如何做到这一点?

【问题讨论】:

  • 您提到要测试这些差异是否显着。那假设您需要进行统计测试?似然比检验通常用于比较不同模型的拟合。 r 中的“lmtest”包就是这样做的。
  • 你能给我一个演示来展示这个吗?

标签: r regression-testing


【解决方案1】:

car 包有一个简单的功能可以做到这一点。

首先,适合您的模型:

model <- lm(Sepal.Length ~ Sepal.Width + Petal.Length, data = iris)

您可以使用linearHypothesis 函数测试不同的线性假设,例如:

library(car)

# tests if the coefficient of Sepal.Width = Petal.Length
linearHypothesis(model, "Sepal.Width = Petal.Length")
Linear hypothesis test

Hypothesis:
Sepal.Width - Petal.Length = 0

Model 1: restricted model
Model 2: Sepal.Length ~ Sepal.Width + Petal.Length

  Res.Df    RSS Df Sum of Sq      F  Pr(>F)  
1    148 16.744                              
2    147 16.329  1    0.4157 3.7423 0.05497 .
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

# Other examples:
# tests if the coefficient of Sepal.Width = 0
linearHypothesis(model, "Sepal.Width = 0")

# tests if the coefficient of Sepal.Width = 0.5
linearHypothesis(model, "Sepal.Width = 0.5")

# tests if both are equal to zero
linearHypothesis(model, c("Sepal.Width = 0", "Petal.Length = 0"))

【讨论】:

  • 如果模型是回归逻辑,包是否有函数,如linearHypothesis?
【解决方案2】:

您可以比较每个模型(例如 mod1 和 mod2)的系数列表,如下所示:

diff=merge(mod1$coefficients, mod2$coefficients, by=0, all=TRUE)
diff[is.na(diff)]=0
diff$error=abs(diff$x-diff$y)
diff[order(diff$error, decreasing=TRUE),]

这会产生一个按系数差的绝对值排序的数据框,即:

    Row.names            x            y        error
1 (Intercept) -0.264189182 -0.060450853 2.037383e-01
6          id  0.003402056  0.000000000 3.402056e-03
3           b -0.001804978 -0.003357193 1.552215e-03
2           a -0.049900767 -0.049417150 4.836163e-04
4           c  0.013749907  0.013819799 6.989203e-05
5           d -0.004097366 -0.004110830 1.346320e-05

如果斜率不是您所追求的,您可以使用 coef() 函数访问其他系数:

coef(summary(model))

要获得 Pr(>|z|),例如,使用:

coef(summary(model))[,"Pr(>|z|)"]

【讨论】:

  • 感谢您的努力,您给出的答案似乎是在测试同一变量在模型之间是否具有相同的斜率。我想得到的是不同的变量是否说a和b在一个模型中具有相同的系数,以及p值是多少。
  • 好的。我对stata不熟悉,所以我没有一个很好的例子。您可以使用 coef() 从 glm 模型访问其他系数参数,如我编辑的答案中所示。但看起来 Carlos 的答案可能更符合您的要求。
猜你喜欢
  • 2020-06-28
  • 2017-09-17
  • 2023-02-11
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多