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

Stata 1:2精确匹配报错r(101):不允许权重,求问题排查

Stata 1:2精确匹配报错r(101)的问题排查

错误根源解析

r(101)“不允许权重”的报错并非真的和权重相关,而是代码存在多处语法、逻辑错误,导致Stata解析命令时出现误判。以下是具体问题和修正方案:

1. 基础语法错误

  • 代码中多处出现多余反引号(),比如`sort treated Sex ChildAge、`local control_prefix "C_"````,这类无效符号会破坏命令结构,干扰Stata的语法解析。
  • HTML转义符号误用:whilematch_found'<2&j'&lt;= _N' 里的<、&是HTML格式的转义符,Stata无法识别,需替换为原生的<、&`。
  • 变量引用格式错误:if treated [i']== 1 中treated[i']的括号前多了空格,正确写法是treated[i']==1`。

2. 观测值引用逻辑错误

  • 匹配条件错误使用_N(总观测数)和_n(当前行观测数):
    if Sex[_N]==Sex[`j']&amp;ChildAge[_n]==ChildAge[`j'] &amp; treated[`j']==0
    
    此处应引用当前病例的观测索引i,即Sex[i']和ChildAge[i'],否则会错误匹配最后一行的性别/年龄,而非当前病例的特征。
  • 替换匹配ID时错误引用_N:replace _match_id[j']= concat(control_prefix', _match_id[_N]) 需改为replace _match_id[j'] = "control_prefix'" + string(_match_id[i'])(Stata用+拼接字符串,concat`不是原生函数)。

3. 循环与宏逻辑错误

  • match_found是循环内的局部宏,循环结束后会失效,无法在循环外用来判断是否删除匹配不足的病例。需在循环内给病例标记match_count变量,记录匹配到的对照数,后续基于该变量筛选病例。
  • 末尾的drop if _n == _N缺少闭合大括号,且逻辑错误,无法正确删除匹配不足的病例。

4. 观测保留逻辑错误

keep if _match_id != . | _match_id like "case_prefix'%" 逻辑有误:初始生成的_match_id是所有观测的行号,病例的_match_id没有前缀,应改为保留treated==1的病例,或_match_id`包含对照前缀的观测,即:

keep if treated == 1 | _match_id like "`control_prefix'%"

修正后的示例代码

* Exact matching on age and sex
sort treated Sex ChildAge

* Generate a matching ID variable and match count tracker
gen _match_id = _n
gen match_count = 0 if treated == 1

local case_prefix "T_"
local control_prefix "C_"

* Loop through cases (children with mental health problems)
forvalues i = 1/`=_N' {
    if treated[`i'] == 1 {
        local match_found = 0
        local j = `i' + 1
        while `match_found' < 2 & `j' <= `=_N' {
            if Sex[`i'] == Sex[`j'] & ChildAge[`i'] == ChildAge[`j'] & treated[`j'] == 0 {
                replace _match_id[`j'] = "`control_prefix'" + string(_match_id[`i'])
                replace match_count[`i'] = match_count[`i'] + 1
                local match_found = `match_found' + 1
            }
            local j = `j' + 1
        }
    }
}

* Drop cases with less than 2 matches
drop if treated == 1 & match_count < 2

* Keep cases and matched controls
keep if treated == 1 | _match_id like "`control_prefix'%"

* Drop temporary variables
drop _match_id match_count

内容的提问来源于stack exchange,提问作者Laura Maragaño

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 07:55:35