如何使用SAS提取每行最后3个非空单元格?
使用SAS提取每行最后3个非空单元格
原始数据集(Data have)
Order_ID,Fruit1,Fruit2,Fruit3,Fruit4,Fruit5 1234,Banana,Peach,Guava,Apple,, 1235,Orange,Grape,,,, 1236,Pear,Papaya,Apricot,,, 1237,Guava,,,,, 1238,Kiwi,Cherry,Peach,Melon,Lime
期望输出数据集(Data want)
Order_ID,Fruit1,Fruit2,Fruit3 1234,Peach,Guava,Apple 1235,Orange,Grape,, 1236,Pear,Papaya,Apricot 1237,Guava,,, 1238,Peach,Melon,Lime
解决方案代码
先创建测试数据集(若已有have数据集可跳过此步):
data have; infile datalines dsd; input Order_ID $ Fruit1 $ Fruit2 $ Fruit3 $ Fruit4 $ Fruit5 $; datalines; 1234,Banana,Peach,Guava,Apple,, 1235,Orange,Grape,,,, 1236,Pear,Papaya,Apricot,,, 1237,Guava,,,,, 1238,Kiwi,Cherry,Peach,Melon,Lime ; run;
提取每行最后3个非空单元格的核心代码:
data want; set have; /* 定义原始水果列的数组 */ array fruits[*] Fruit1-Fruit5; /* 定义输出的3个水果列数组,直接复用原变量名 */ array new_fruits[3] $ Fruit1-Fruit3; /* 初始化输出变量为空值 */ call missing(of new_fruits[*]); count = 0; /* 从最后一列倒序遍历,收集非空值 */ do i = dim(fruits) down to 1; if not missing(fruits[i]) then do; count + 1; /* 将非空值按顺序放入输出数组的对应位置 */ new_fruits[4 - count] = fruits[i]; /* 收集够3个非空值后停止遍历 */ if count = 3 then leave; end; end; /* 删除临时变量 */ drop i count; run;
代码说明
- 用
array批量处理水果列,避免逐个变量判断,提升代码效率 - 倒序遍历确保优先获取最右侧的非空值,精准匹配“最后3个”的需求
- 通过计数器控制只保留最后3个非空值,不足3个时保留所有非空值并自动补空
- 直接复用原变量名
Fruit1-Fruit3,完全匹配期望的输出格式
内容的提问来源于stack exchange,提问作者Sheldon
相关产品推荐
相关产品推荐

