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

Stata中用for loop批量执行Logistic回归并预测值与残差

用Stata循环批量执行逐步加入自变量的Logistic回归及预测

实现思路

先将需要逐步加入的自变量存入局部宏,通过循环依次选取前N个变量构建回归模型,每次回归后自动生成对应序号的预测值和残差变量。

示例代码

* 1. 定义待逐步加入的自变量列表(替换为你的实际变量名)
local x_vars x-variable1 x-variable2 x-variable3 x-variable4

* 2. 自动统计自变量总数
local num_x : word count `x_vars'

* 3. 循环执行逐步回归与预测操作
forvalues i = 1/`num_x' {
    * 提取当前循环对应的前i个自变量
    local current_x : word 1/`i' of `x_vars'
    
    * 执行Logistic回归
    logit y-variable `current_x'
    
    * 生成对应序号的预测值(变量名:values1、values2...)
    predict values`i'
    
    * 生成对应序号的残差(变量名:residuals1、residuals2...)
    predict residuals`i', res
}

代码说明

  • local x_vars:把所有要逐步加入的自变量统一存入局部宏,后续可直接调用,你只需替换成自己的变量名即可。
  • local num_x : word count x_vars'':自动计算自变量的总个数,无需手动指定循环上限,适配不同数量的自变量场景。
  • forvalues i = 1/num_x'`:从1开始循环到自变量总数,每次循环对应“加入第i个自变量”的回归操作。
  • local current_x : word 1/i' of x_vars':每次循环提取前i个自变量,实现逐步加入变量的效果。
  • 两次predict命令通过values`i'和residuals`i'自动生成带序号的变量,和你手动编写的单步代码效果完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:30:53