我想通过创建一个向量来总结一个数据集,该向量提供了在哪些部门中找到id的信息。例如,
data test;
input id dept $;
datalines;
1 A
1 D
1 B
1 C
2 C
3 D
4 A
5 C
5 D
;
run;
我想要
id dept_vect
1 1111
2 0010
3 0001
4 1000
5 1001
dept_vect元素的位置是按字母顺序排列的。因此,第一个位置中的'1‘表示id在第A部分中找到,而'1’在第二个位置表示id在B部门中找到。‘A '0’表示在部门中找不到id。
我可以用蛮力法解决这个问题。
proc transpose data = test out = test1(drop = _NAME_);
by id;
var dept;
run;
data test2;
set test1;
array x[4] $ col1-col4;
array d[4] $ d1-d4;
do i = 1 to 4;
if not missing(x[i]) then do;
if x[i] = 'A' then d[1] = 1;
else if x[i] = 'B' then d[2] = 1;
else if x[i] = 'C' then d[3] = 1;
else if x[i] = 'D' then d[4] = 1;
end;
else leave;
end;
do i = 1 to 4;
if missing(d[i]) then d[i] = 0;
end;
dept_id = compress(d1) || compress(d2) || compress(d3) || compress(d4);
keep id dept_id;
run;
这是可行的,但也有一些问题。要使col4出现,我至少需要在所有部门中找到一个id,但是可以通过创建一个虚拟id来修复这个id,以便在所有部门上找到id。但是主要的问题是这段代码不健壮。是否有一种方法对此进行编码,使其能够适用于任意数量的部门?
发布于 2019-06-05 17:26:08
发布于 2019-06-06 07:32:40
也许TRANSREG能帮上忙。
data test;
input id dept $;
datalines;
1 A
1 D
1 B
1 C
2 C
3 D
4 A
5 C
5 D
;
run;
proc transreg;
id id;
model class(dept / zero=none);
output design out=dummy(drop=dept);
run;
proc print;
run;
proc summary nway;
class id;
output out=want(drop=_type_) max(dept:)=;
run;
proc print;
run;
https://stackoverflow.com/questions/56469317
复制相似问题