我有一个SAS数据集,其中每一行都包含关于公司的信息。关于公司的部门有一个变量;有多达700个部门,所以我需要对它们进行分组,例如:
工业:矿业,纺织业,食品工业.诸若此类。我这样做的代码如下:
data temp; set in.data;
if sect in ('01' '02' '03' '04' '05' '06') then my_sector='Industry' ;
run;
棘手的部分是,我也想给出每个部门的细节。举例来说,我想保留整个“工业”界别,但我也希望在“工业”内有分组。但是,当我运行以下代码时:
data temp; set in.data;
if sect in ('01' '02' '03' '04' '05' '06') then my_sector='Industry' ;
if sect in ('01' '02') then my_sector='Textile Industry' ;
if sect in ('03' '04') then my_sector='Food Industry' ;
if sect in ('05') then my_sector='Mining Industry' ;
run;
这些子组工作得很好,但是全球“工业”部门只包含其他子组中没有包含的内容(这里是扇区06)。因此,我的问题是,我如何拥有这3个组别,但又是一个“工业”界别,包括所有3个组别及其他行业(由01至06年度)?
非常感谢,
发布于 2019-12-02 11:55:10
在执行完第一次if-statement
之后,您将覆盖变量的值。您应该使用其他变量或output
语句:
data want; set have;
length my_sector $20;
if sect in ('01' '02' '03' '04' '05' '06') then do;
my_sector='Industry' ;
output;
if sect in ('01' '02') then do;
my_sector='Textile Industry' ;
output;
end;
if sect in ('03' '04') then do;
my_sector='Food Industry' ;
output;
end;
if sect in ('05') then do;
my_sector='Mining Industry' ;
output;
end;
end;
run;
拥有数据集:
+------+
| sect |
+------+
| 01 |
| 02 |
| 03 |
| 04 |
| 05 |
| 06 |
+------+
想要数据集:
+------+------------------+
| sect | my_sector |
+------+------------------+
| 01 | Industry |
| 01 | Textile Industry |
| 02 | Industry |
| 02 | Textile Industry |
| 03 | Industry |
| 03 | Food Industry |
| 04 | Industry |
| 04 | Food Industry |
| 05 | Industry |
| 05 | Mining Industry |
| 06 | Industry |
+------+------------------+
发布于 2019-12-02 20:41:41
就.而言
I也希望有子组
您会想要将“sect”映射到两个变量层次结构中,例如父级、“工业”级和子级级“扇区”。
通常,映射的控制最好放在控制表中,当新的或附加的“sect”值发挥作用时,可以轻松地处理行业和部门名称。
data sect_mappings; length sect $2 group $8 sector $8; input
sect group sector; datalines;
01 Industry Textile
02 Industry Textile
03 Industry Food
04 Industry Food
05 Industry Mining
run;
可以将控制表留在原始数据上,以便将'sect‘值映射到'group’和‘扇形’名称(即sect
的格式化值)。
SAS中最强大的特性之一是自定义格式的概念,因此您实际上可以不使用sect
值,并根据格式化的值自动处理它。
可以直接从映射表创建自定义格式。在您的示例中,您需要两种自定义格式,一种用于将sect
映射到group
,另一种用于将sect
映射到sector
。
data sector_cntlin;
set sect_mappings;
rename sect=start;
fmtname = '$sect_group'; label=group; output;
fmtname = '$sect_name' ; label=sector; output;
run;
proc sort data=sector_cntlin;
by fmtname;
run;
proc format cntlin=sector_cntlin;
run;
这些格式可用于在聚合信息时使用sect
作为by
或class
变量的SAS过程。
假设您有示例数据:
data have;
call streaminit(123);
do company_id = 1 to 100;
sect = put(ceil(rand('uniform', 10)), z2.);
output;
end;
run;
为了具有两层层次结构(使用格式化的值),您将需要一个重复sect
值的附加变量。
data want;
set have;
sect_repeat = sect;
run;
此时,如果sect
和sect_repeat
变量是class
变量,则SAS过程处理两级层次结构中的数据。
proc tabulate data=want;
class sect sect_repeat;
format sect $sect_group.;
format sect_repeat $sect_name.;
label sect = 'Group';
label sect_repeat = 'Sector';
table
sect * (all sect_repeat)
, n
/ nocellmerge
;
run;
输出报告,如下所示。sect
的未映射值是显而易见的,可以添加到映射表中,也可以使用where
语句过滤掉。
https://stackoverflow.com/questions/59138056
复制相似问题