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

如何在SAS中将两个变量数据转为两行并保留第三变量值

SAS实现多列账号转多行记录

需求说明:现有SAS数据集包含Acct_nb(主账号)、repl_acct_nb(备用账号)、amount(金额)三个变量,需要生成新变量new_acct_nb,将主账号和备用账号的非缺失值拆分为独立行,同时保留对应金额值。

输入数据集(数据集名:have)

Acct_nb repl_acct_nb amount
12334       45678     100
23456       .         200

期望输出数据集(数据集名:want)

new_acct_nb amount
12334       100
45678       100
23456       200

解决方案1:DATA步逐列判断输出

逻辑直观,适合仅处理固定两列的场景:

data want;
    set have;
    /* 输出主账号行 */
    if not missing(Acct_nb) then do;
        new_acct_nb = Acct_nb;
        output;
    end;
    /* 输出备用账号行(仅当非缺失时) */
    if not missing(repl_acct_nb) then do;
        new_acct_nb = repl_acct_nb;
        output;
    end;
    /* 保留目标变量 */
    keep new_acct_nb amount;
run;

解决方案2:DATA步数组循环(扩展性更强)

如果后续需要处理更多账号列,用数组循环更灵活,只需修改数组定义即可:

data want;
    set have;
    /* 定义数组包含所有需要拆分的账号列 */
    array acct_cols[2] Acct_nb repl_acct_nb;
    /* 遍历数组,输出非缺失的账号行 */
    do i = 1 to dim(acct_cols);
        new_acct_nb = acct_cols[i];
        if not missing(new_acct_nb) then output;
    end;
    /* 保留目标变量,删除临时变量i */
    keep new_acct_nb amount;
    drop i;
run;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:45:41