[英]Get the unique combinations per variable in SAS
我正在嘗試將一個不唯一的變量與一個離散變量進行分組,以獲取每個非唯一變量的唯一組合。 例如:
A B
1 a
1 b
2 a
2 a
3 a
4 b
4 d
5 c
5 e
我想要:
A Unique_combos
1 a, b
2 a
3 a
4 b, d
5 e
我目前的嘗試是:
proc sql outobs=50;
title 'Unique Combinations of b per a';
select a, b
from mylib.mydata
group by distinct a;
run;
如果您樂意使用數據步驟而不是proc sql
,則可以將retain
關鍵字與first / last處理結合使用:
示例數據:
data have;
attrib b length=$1 format=$1. informat=$1.;
input a
b $
;
datalines;
1 a
1 b
2 a
2 a
3 a
4 b
4 d
5 c
5 e
;
run;
消除重復,並確保對數據進行排序以進行第一個/最后一個處理:
proc sql noprint;
create table tmp as select distinct a,b from have order by a,b;
quit;
遍歷唯一列表並將b的值連接在一起:
data want;
length combinations $200; * ADJUST TO BE BIG ENOUGH TO STORE ALL THE COMBINATIONS;
set tmp;
by a;
retain combinations '';
if first.a then do;
combinations = '';
end;
combinations = catx(', ',combinations, b);
if last.a then do;
output;
end;
drop b;
run;
結果:
combinations a
a, b 1
a 2
a 3
b, d 4
c, e 5
您只需要在select
子句中放入一個distinct
關鍵字,例如:
title 'Unique Combinations of b per a';
proc sql outobs=50;
select distinct a, b
from mylib.mydata;
run
語句是不必要的,sql過程通常以quit
結尾-盡管我個人從未使用過該語句,因為該語句將在擊中分號時執行,而該過程在擊中下一步邊界時仍然退出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.