【问题标题】:linear regression r comparing multiple observations vs single observation线性回归 r 比较多个观察值与单个观察值
【发布时间】:2016-08-08 02:40:43
【问题描述】:

根据我的question 的答案,我应该得到相同的截距值和以下 2 个模型的回归系数。但它们并不相同。到底是怎么回事?

我的代码有问题吗?还是原来的答案错了?

#linear regression average qty per price point vs all quantities

x1=rnorm(30,20,1);y1=rep(3,30)
x2=rnorm(30,17,1.5);y2=rep(4,30)
x3=rnorm(30,12,2);y3=rep(4.5,30)
x4=rnorm(30,6,3);y4=rep(5.5,30)
x=c(x1,x2,x3,x4)
y=c(y1,y2,y3,y4)
plot(y,x)
cor(y,x)
fit=lm(x~y)
attributes(fit)
summary(fit)

xdum=c(20,17,12,6)
ydum=c(3,4,4.5,5.5)
plot(ydum,xdum)
cor(ydum,xdum)
fit1=lm(xdum~ydum)
attributes(fit1)
summary(fit1)


> summary(fit)

Call:
lm(formula = x ~ y)

Residuals:
    Min      1Q  Median      3Q     Max 
-8.3572 -1.6069 -0.1007  2.0222  6.4904 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  40.0952     1.1570   34.65   <2e-16 ***
y            -6.1932     0.2663  -23.25   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 2.63 on 118 degrees of freedom
Multiple R-squared:  0.8209,    Adjusted R-squared:  0.8194 
F-statistic: 540.8 on 1 and 118 DF,  p-value: < 2.2e-16

> summary(fit1)

Call:
lm(formula = xdum ~ ydum)

Residuals:
      1       2       3       4 
-0.9615  1.8077 -0.3077 -0.5385 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)   
(Intercept)  38.2692     3.6456  10.497  0.00895 **
ydum         -5.7692     0.8391  -6.875  0.02051 * 
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.513 on 2 degrees of freedom
Multiple R-squared:  0.9594,    Adjusted R-squared:  0.9391 
F-statistic: 47.27 on 1 and 2 DF,  p-value: 0.02051

【问题讨论】:

  • 您正在使用正态分布的随机抽取 - rnorm - 与采用完美指定的值相比,您的结果将始终是模糊的。看mean(x1)mean(x2)

标签: r regression lm


【解决方案1】:

您没有以可比较的方式计算xdumydum,因为rnorm 只会逼近您指定的平均值,尤其是当您仅抽样30 个案例时。然而,这很容易解决:

coef(fit)
#(Intercept)           y 
#  39.618472   -6.128739 

xdum <- c(mean(x1),mean(x2),mean(x3),mean(x4))
ydum <- c(mean(y1),mean(y2),mean(y3),mean(y4))
coef(lm(xdum~ydum))
#(Intercept)        ydum 
#  39.618472   -6.128739 

【讨论】:

  • coef(lm(sapply(mget(paste0("x", 1:4)), mean)~sapply(mget(paste0("y", 1:4)), mean)))
【解决方案2】:

理论上,当(且仅当)前一个模型的平均值等于后一个模型中的点时,它们应该是相同的。

您的模型并非如此,因此结果略有不同。比如x1的平均值:

x1=rnorm(30,20,1)
mean(x1)

20.08353

其中点版本为 20。

与您的其他 rnorm 样本有类似的微小差异:

> mean(x2)
[1] 17.0451
> mean(x3)
[1] 11.72307
> mean(x4)
[1] 5.913274

这并不重要,但仅供参考,标准命名法是 Y 是因变量,X 是自变量,你颠倒了。当然没有区别,但只是让你知道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 2019-12-28
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    相关资源
    最近更新 更多