r - 在线性回归模型中包含误差项

标签 r linear-regression

我想知道是否有办法为线性回归模型包含误差项,例如:

r = lm(y ~ x1+x2)

最佳答案

代码r = lm(y ~ x1+x2)意味着我们将 y 建模为 x1 和 x2 的线性函数。由于模型不会是完美的,因此会有一个残差项(即模型未能拟合的剩余项)。

在数学方面,正如 Rob Hyndman 在评论中指出的,y = a + b1*x1 + b2*x2 + e ,其中 a , b1b2是常数和 e是您的残差(假设为正态分布)。

为了看一个具体的例子,考虑 R 附带的虹膜数据。

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

现在我们可以从模型中提取常量(相当于 ab1b2 ,在本例中也是 b3 )。
> coefficients(model1)
(Intercept)  Sepal.Width Petal.Length  Petal.Width 
1.8559975    0.6508372    0.7091320   -0.5564827

已为模型中使用的每一行数据计算残差。
> residuals(model1)
           1             2             3             4             5       
0.0845842387  0.2100028184 -0.0492514176 -0.2259940935 -0.0804994772
# etc. There are 150 residuals and 150 rows in the iris dataset.

(编辑:将摘要信息剪切为不相关。)

编辑:
Error您在 aov 的帮助页面上解释的评论中提到的值(value)。
If the formula contains a single ‘Error’ term, this is used to
specify error strata, and appropriate models are fitted within
each error stratum.

比较以下内容(改编自 ?aov 页面。)
> utils::data(npk, package="MASS")
> aov(yield ~  N*P*K, npk)
Call:
   aov(formula = yield ~ N * P * K, data = npk)

Terms:
                       N        P        K      N:P      N:K      P:K    N:P:K Residuals
Sum of Squares  189.2817   8.4017  95.2017  21.2817  33.1350   0.4817  37.0017  491.5800
Deg. of Freedom        1        1        1        1        1        1        1        16

Residual standard error: 5.542901 
Estimated effects may be unbalanced

> aov(yield ~  N*P*K + Error(block), npk)
Call:
aov(formula = yield ~ N * P * K + Error(block), data = npk)

Grand Mean: 54.875 

Stratum 1: block

Terms:
                    N:P:K Residuals
Sum of Squares   37.00167 306.29333
Deg. of Freedom         1         4

Residual standard error: 8.750619 
Estimated effects are balanced

Stratum 2: Within

Terms:
                        N         P         K       N:P       N:K       P:K Residuals
Sum of Squares  189.28167   8.40167  95.20167  21.28167  33.13500   0.48167 185.28667
Deg. of Freedom         1         1         1         1         1         1        12

Residual standard error: 3.929447 
1 out of 7 effects not estimable
Estimated effects may be unbalanced

关于r - 在线性回归模型中包含误差项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1801487/

相关文章:

r - 如何更改 ggplot 中这个定制设计图例的背景颜色?

python - sklearn LinearRegression报错

c# - 具有动态数据显示的 WPF 图表 : How can I show a regression line?

python - 为什么参数的数量与分类变量的数量不同?

r - 错误 : could not find function "read.DNAStringSet"

R ggplot2 有交互选项吗?

javascript - 如何用 R 解析 javascript 数据列表

python - 将函数应用于多索引多列数据帧的 Pythonic 方法是什么?

python - 为什么看不到回归线?

r ggplot 动态使用 plotmath 表达式