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

如何在SAS中标记非缺失列间存在缺失列的数据行?

SAS标记非缺失列间存在缺失值的行

原始数据集

data Have;
input col1 $ col2 $ col3 $ col4 $ col5 $ col6 $ col7 $ col8 $ col9 $ col10 $;
cards;
A B B C . D A . A . 
B A . C A D A B . . 
A B B D D D . . . . 
A . B C B D A . . . 
A B B C . D A . . . 
;
run;

需求说明

标记所有在第一个非缺失列与最后一个非缺失列之间存在缺失列的数据行,忽略行尾连续缺失的情况。

解决方案代码

data Want;
    set Have;
    array cols[*] col1-col10;
    length first_nonmiss last_nonmiss 8;
    flag = 0;

    /* 定位第一个非缺失列的位置 */
    do i = 1 to dim(cols);
        if not missing(cols[i]) then do;
            first_nonmiss = i;
            leave;
        end;
    end;

    /* 定位最后一个非缺失列的位置 */
    do i = dim(cols) to 1 by -1;
        if not missing(cols[i]) then do;
            last_nonmiss = i;
            leave;
        end;
    end;

    /* 检查首尾非缺失列之间是否存在缺失值 */
    if first_nonmiss < last_nonmiss then do;
        do i = first_nonmiss + 1 to last_nonmiss - 1;
            if missing(cols[i]) then do;
                flag = 1;
                leave;
            end;
        end;
    end;

    drop i first_nonmiss last_nonmiss;
run;

代码解释

  1. 数组批量处理:用array cols[*] col1-col10将所有目标列存入数组,简化多列遍历操作。
  2. 首尾位置定位:
    • 正向遍历数组,找到第一个非缺失值的列位置first_nonmiss
    • 反向遍历数组,找到最后一个非缺失值的列位置last_nonmiss
  3. 标记逻辑判断:若首尾位置不同(即存在至少两个非缺失列),遍历两者之间的列,一旦发现缺失值就将flag设为1并终止检查。
  4. 冗余变量清理:删除中间临时变量,避免数据集冗余。

运行代码后得到的Want数据集,将包含符合预期的flag标记列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 04:37:15