You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

当自变量与因变量相同时,线性模型为何未返回斜率和R平方?

为何将同一变量同时作为自变量和因变量时,线性回归未返回斜率1和R²=1?

我有一个数据框,做线性回归分析时,把同一个变量既当因变量又当自变量,结果模型摘要没返回预期的斜率1和R平方值1,只输出了截距。这是为什么?

复现代码及运行结果

aa <- data.frame(x = rnorm(10, 100, 5),
                 y = rnorm(10,500, 2))

lm_mod1 <- lm(y~x, data = aa)
summary(lm_mod1) # 正常运行,返回斜率和R平方值
#> 
#> Call:
#> lm(formula = y ~ x, data = aa)
#> 
#> Residuals:
#>     Min      1Q  Median      3Q     Max 
#> -4.0241 -1.3874  0.5264  1.7933  2.2946 
#> 
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)    
#> (Intercept) 489.7413    14.2402  34.391 5.59e-10 ***
#> x             0.1008     0.1428   0.706      0.5    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 2.491 on 8 degrees of freedom
#> Multiple R-squared:  0.05862,    Adjusted R-squared:  -0.05905 
#> F-statistic: 0.4982 on 1 and 8 DF,  p-value: 0.5003

lm_mod2 <- lm(x~x, data = aa)
#> Warning in model.matrix.default(mt, mf, contrasts): the response appeared on the
#> right-hand side and was dropped
#> Warning in model.matrix.default(mt, mf, contrasts): problem with term 1 in
#> model.matrix: no columns are assigned
summary(lm_mod2) # 未返回斜率或R平方值
#> 
#> Call:
#> lm(formula = x ~ x, data = aa)
#> 
#> Residuals:
#>      Min       1Q   Median       3Q      Max 
#> -10.6993  -2.9903  -0.6496   3.2495   8.4294 
#> 
#> Coefficients:
#>             Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)   99.554      1.838   54.16 1.25e-12 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> Residual standard error: 5.813 on 9 degrees of freedom

原因及解决办法

  • 核心原因:R的lm()函数会自动检测并移除公式中等式两侧的同一变量,避免完全共线性问题——当自变量和因变量完全相同时,二者相关系数为1,会导致设计矩阵不可逆,无法计算回归系数。运行lm(x~x, data=aa)时,函数已明确提示the response appeared on the right-hand side and was dropped(因变量出现在右侧,被移除),此时模型退化为仅拟合截距的lm(x~1, data=aa),截距值就是x的均值。
  • 解决办法:如果要得到预期的斜率1和R²=1,需要用不同变量名指代同一数据,比如创建一个和x完全相同的新变量:
aa$x_copy <- aa$x
lm_mod3 <- lm(x ~ x_copy, data = aa)
summary(lm_mod3)

此时R会将x和x_copy视为不同变量,不会自动移除,模型会拟合出斜率1,R²=1。


内容的提问来源于stack exchange,提问作者tassones

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 18:23:18