如何完善SAS代码以根据前置分组值补全表格color列?
SAS数据分组填充问题解决
问题说明
现有一份文本数据,首行是分组名称(如Blars、Klirs),后续是对应的数据行。需要完善SAS代码,将分组名称填充到对应数据行的color列,最终输出包含cr、ls、ms、color四列的数据集。
初始代码框架如下:
data ms; infile 'C'; input cr ls ms color $; if input @; *statemet that reads the line with one word and complete the color column* run;
输入数据
Blars 10 83287 10.00 20 1748956 30.00 30 2222222 73.00 40 833709 90.00 Klirs 10 922222 90.50 20 1222222 10.00 30 1111111 93.33 40 8998877 300.90
期望输出
| cr | ls | ms | color |
|---|---|---|---|
| 10 | 83287 | 10.00 | Blars |
| 20 | 1748956 | 30.00 | Blars |
| 30 | 2222222 | 73.00 | Blars |
| 40 | 833709 | 90.00 | Blars |
| 10 | 922222 | 90.50 | Klirs |
| 20 | 1222222 | 10.00 | Klirs |
| 30 | 1111111 | 93.33 | Klirs |
| 40 | 8998877 | 300.90 | Klirs |
修正后的SAS代码
data ms; infile 'C' truncover; /* 处理行尾数据长度不足的情况 */ retain color; /* 保留分组名称,直到遇到新的分组头 */ input @1 cr ?? best32.; /* 尝试读取cr,失败则判定为分组行 */ if missing(cr) then do; input @1 color $; /* 读取当前行的分组名称 */ delete; /* 不输出分组头行 */ end; else do; input ls ms; /* 读取数据行的剩余字段 */ end; run;
代码解释
retain color:让分组名称在后续数据行中持续生效,直到下一个分组头出现。input @1 cr ?? best32.:从行首尝试读取数值型变量cr,??表示读取失败时不触发报错,此时说明当前行是分组名称行。- 当
cr缺失时,读取分组名称到color变量,并用delete跳过该行输出。 - 当
cr存在时,读取ls和ms字段,此时color已被保留为当前分组名称,直接输出该行即可。 truncover:适配数据行中字段位置不固定的情况,确保所有数据被正确读取。
内容的提问来源于stack exchange,提问作者stat
相关产品推荐
相关产品推荐

