R和Stata中没有截距的回归

如何解决R和Stata中没有截距的回归

最近,我偶然发现了一个事实,即 Stata 和 R 以不同的方式处理回归而没有截距。我不是统计学家,所以如果我的词汇量不理想,请多多包涵。

我试图使示例具有一定的可重现性。这是我在 R 中的示例:

> set.seed(20210211)
> df <- data.frame(y = runif(50),x = runif(50))
> df$d <- df$x > 0.5
> 
> (tmp <- tempfile("data",fileext = ".csv"))
[1] "C:\\Users\\s1504gl\\AppData\\Local\\Temp\\1\\RtmpYtS6uk\\data1b2c1c4a96.csv"
> write.csv(df,tmp,row.names = FALSE)
> 
> summary(lm(y ~ x + d,data = df))

Call:
lm(formula = y ~ x + d,data = df)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.48651 -0.27449  0.03828  0.22119  0.53347 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)   0.4375     0.1038   4.214 0.000113 ***
x            -0.1026     0.3168  -0.324 0.747521    
dTRUE         0.1513     0.1787   0.847 0.401353    
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.2997 on 47 degrees of freedom
Multiple R-squared:  0.03103,Adjusted R-squared:  -0.0102 
F-statistic: 0.7526 on 2 and 47 DF,p-value: 0.4767

> summary(lm(y ~ x + d + 0,data = df))

Call:
lm(formula = y ~ x + d + 0,data = df)

Residuals:
     Min       1Q   Median       3Q      Max 
-0.48651 -0.27449  0.03828  0.22119  0.53347 

Coefficients:
       Estimate Std. Error t value Pr(>|t|)    
x       -0.1026     0.3168  -0.324 0.747521    
dFALSE   0.4375     0.1038   4.214 0.000113 ***
dTRUE    0.5888     0.2482   2.372 0.021813 *  
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 0.2997 on 47 degrees of freedom
Multiple R-squared:  0.7196,Adjusted R-squared:  0.7017 
F-statistic: 40.21 on 3 and 47 DF,p-value: 4.996e-13

这是我在 Stata 中的内容(请注意,我已将文件名从 R 复制到 Stata):


. import delimited "C:\Users\s1504gl\AppData\Local\Temp\1\RtmpYtS6uk\data1b2c1c4a96.csv"
(3 vars,50 obs)

. encode d,generate(d_enc)

. 
. regress y x i.d_enc

      Source |       SS           df       MS      Number of obs   =        50
-------------+----------------------------------   F(2,47)        =      0.75
       Model |  .135181652         2  .067590826   Prob > F        =    0.4767
    Residual |  4.22088995        47  .089806169   R-squared       =    0.0310
-------------+----------------------------------   Adj R-squared   =   -0.0102
       Total |   4.3560716        49   .08889942   Root MSE        =    .29968

------------------------------------------------------------------------------
           y |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |  -.1025954   .3168411    -0.32   0.748    -.7399975    .5348067
             |
       d_enc |
       TRUE  |   .1512977   .1786527     0.85   0.401    -.2081052    .5107007
       _cons |   .4375371    .103837     4.21   0.000     .2286441    .6464301
------------------------------------------------------------------------------

. regress y x i.d_enc,noconstant

      Source |       SS           df       MS      Number of obs   =        50
-------------+----------------------------------   F(2,48)        =     38.13
       Model |  9.23913703         2  4.61956852   Prob > F        =    0.0000
    Residual |  5.81541777        48  .121154537   R-squared       =    0.6137
-------------+----------------------------------   Adj R-squared   =    0.5976
       Total |  15.0545548        50  .301091096   Root MSE        =    .34807

------------------------------------------------------------------------------
           y |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
           x |    .976214   .2167973     4.50   0.000     .5403139    1.412114
             |
       d_enc |
       TRUE  |  -.2322011   .1785587    -1.30   0.200    -.5912174    .1268151
------------------------------------------------------------------------------

如您所见,带截距的回归结果是相同的。但是如果我省略拦截(R 中的 + 0,Stata 中的 ,noconstant),结果会有所不同。在 R 中,拦截现在在 dFALSE 中捕获,根据我的理解这是合理的。我不明白Stata在这里做什么。自由度也不同。

我的问题:

  1. 谁能向我解释一下 Stata 是如何处理这个问题的?
  2. 如何在 R 中复制 Stata 的行为?

解决方法

我相信 bas 指向了正确的方向,但我仍然不确定为什么这两个结果不同。

我不是要回答这个问题,而是要更深入地了解 stata 正在做什么(通过深入研究 R 的 lm() 函数的来源。在以下几行中,我复制了 lm() 的作用,但是跳过健全性检查和选项,例如权重、对比度等......

(我还不能完全理解为什么在第二次回归(没有常数)中,dFALSE 系数捕获了默认回归(常数)中截距的影响

set.seed(20210211)
df <- data.frame(y = runif(50),x = runif(50))
df$d <- df$x > 0.5

lm() 常量

form_default <- as.formula(y ~ x + d)
mod_frame_def <- model.frame(form_default,df)
mod_matrix_def <- model.matrix(object = attr(mod_frame_def,"terms"),mod_frame_def)
head(mod_matrix_def)
#>   (Intercept)         x dTRUE
#> 1           1 0.7861162     1
#> 2           1 0.2059603     0
#> 3           1 0.9793946     1
#> 4           1 0.8569093     1
#> 5           1 0.8124811     1
#> 6           1 0.7769280     1

stats:::lm.fit(
  y = model.response(mod_frame_def),x = mod_matrix_def
)$coefficients
#> (Intercept)           x       dTRUE 
#>   0.4375371  -0.1025954   0.1512977

lm() 无常量

form_nocon  <- as.formula(y ~ x + d + 0)
mod_frame_nocon <- model.frame(form_nocon,df)
mod_matrix_nocon <- model.matrix(object = attr(mod_frame_nocon,mod_frame_nocon)
head(mod_matrix_nocon)
#>           x dFALSE dTRUE
#> 1 0.7861162      0     1
#> 2 0.2059603      1     0
#> 3 0.9793946      0     1
#> 4 0.8569093      0     1
#> 5 0.8124811      0     1
#> 6 0.7769280      0     1

stats:::lm.fit(
  y = model.response(mod_frame_nocon),x = mod_matrix_nocon
)$coefficients
#>          x     dFALSE      dTRUE 
#> -0.1025954  0.4375371  0.5888348

lm() 和 as.numeric()

[如bas的评论所示]

form_asnum  <- as.formula(y ~ x + as.numeric(d) + 0)
mod_frame_asnum <- model.frame(form_asnum,df)
mod_matrix_asnum <- model.matrix(object = attr(mod_frame_asnum,mod_frame_asnum)
head(mod_matrix_asnum)
#>           x as.numeric(d)
#> 1 0.7861162             1
#> 2 0.2059603             0
#> 3 0.9793946             1
#> 4 0.8569093             1
#> 5 0.8124811             1
#> 6 0.7769280             1

stats:::lm.fit(
  y = model.response(mod_frame_asnum),x = mod_matrix_asnum
)$coefficients
#>             x as.numeric(d) 
#>     0.9762140    -0.2322012

reprex package (v1.0.0) 于 2021 年 3 月 18 日创建

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-