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

如何用SAS代码按ID生成标识是否同时存在E10和E11组合的新变量

需求实现:按ID标记是否同时存在指定VALUE组合

原始数据集

IDCASEVALUEDUMMY
1234736E101
1231254N650
1230997E111
1237655x0
9871234x0
9876376E101
9870980E180

需求说明

需要新增名为Has the combination的字段,规则为:

  • 若同一ID的VALUE字段中同时存在E10和E11,则该ID下所有行的此字段值为1
  • 否则为0

预期输出

IDCASEVALUEDUMMYHas the combination
1234736E1011
1231254N6501
1230997E1111
1237655x01
9871234x00
9876376E1010
9870980E1800

实现方案

1. SQL实现

核心思路:先分组统计每个ID是否同时包含E10和E11,再将结果关联回原表。

WITH id_check AS (
    SELECT 
        ID,
        CASE 
            WHEN SUM(CASE WHEN VALUE = 'E10' THEN 1 ELSE 0 END) > 0 
                 AND SUM(CASE WHEN VALUE = 'E11' THEN 1 ELSE 0 END) > 0 
            THEN 1 
            ELSE 0 
        END AS Has_the_combination
    FROM your_table
    GROUP BY ID
)
SELECT 
    t.ID,
    t.CASE,
    t.VALUE,
    t.DUMMY,
    ic.Has_the_combination
FROM your_table t
JOIN id_check ic ON t.ID = ic.ID;

2. Python Pandas实现

核心思路:用groupby结合transform,一次性给每个ID的所有行标记结果。

import pandas as pd

# 假设原始数据已加载到df中
df = pd.DataFrame({
    'ID': [123,123,123,123,987,987,987],
    'CASE': [4736,1254,997,7655,1234,6376,980],
    'VALUE': ['E10','N65','E11','x','x','E10','E18'],
    'DUMMY': [1,0,1,0,0,1,0]
})

# 新增目标字段
df['Has the combination'] = df.groupby('ID')['VALUE'].transform(
    lambda x: 1 if ('E10' in x.values and 'E11' in x.values) else 0
)

print(df)

3. SAS实现

核心思路:按ID排序后,用RETAIN变量记录当前ID的E10/E11存在状态,再批量赋值。

proc sort data=your_data;
    by ID;
run;

data final_data;
    set your_data;
    by ID;
    retain has_e10 has_e11;
    if first.ID then do;
        has_e10 = 0;
        has_e11 = 0;
    end;
    if VALUE = 'E10' then has_e10 = 1;
    if VALUE = 'E11' then has_e11 = 1;
    Has_the_combination = (has_e10 and has_e11);
    if last.ID then do;
        do until(last.ID);
            output;
            set your_data;
            by ID;
            Has_the_combination = (has_e10 and has_e11);
        end;
        output;
    end;
    drop has_e10 has_e11;
run;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 08:25:03