How do you add a row Number in SAS by multiple groups with one variable in decending order?

扶醉桌前 提交于 2021-01-29 09:28:40

问题


I have discovered this code in SAS that mimics the following window function in SQL server:

ROW_NUMBER() OVER (PARTITION BY Var1,var2 ORDER BY var1, var2) 

=

data want;
set have
by  var1  var2;
if first.var1 AND first.var2 then n=1;
else n+1;
run;

"She's a beaut' Clark"... but, How does one mimic this operation:

ROW_NUMBER() OVER (PARTITION BY Var1,var2 ORDER BY var1, var2 Desc)

I've made sure I have before:

PROC SORT DATA=WORK.TEST
OUT=WORK.TEST;
BY var1 DECENDING var2  ;
RUN;

data WORK.want;
set WORK.Test;
by  var1 var2;
if first.var1 AND last.var2 then n=1;
else n+1;
run;

But this doesn't work.

ERROR: BY variables are not properly sorted on data set WORK.TEST.

Sample DataSet:

data test;   
infile datalines dlm='#';
INPUT var1 var2;
datalines;
1#5 
2#4
1#3
1#6
1#9 
2#5 
2#2 
1#7
; 
run; 

I was thinking I can make one variable temporary negative, but I don't want to change the data, I'm looking for a more elegant solution.


回答1:


You have to tell the data step to expect the data in descending order if that is what you are giving it.

You also don't seem to quite get the logic of the FIRST. and LAST. flags. If it is FIRST.VAR1 then by definition it is FIRST.VAR2. The first observation for this value of VAR1 is also the first observation for the first value of VAR2 within this specific value of VAR1.

Do you want to number the observations within each combination of VAR1 and VAR2?

data WORK.want;
  set WORK.Test;
  BY var1 DESCENDING var2  ;
  if first.var2 then n=1;
  else n+1;
run;

Or number the distinct values of VAR2 within VAR1?

data WORK.want;
  set WORK.Test;
  BY var1 DESCENDING var2  ;
  if first.var1 then n=0;
  if first.var2 then n+1;
run;

Or number the distinct combinations of VAR2 and VAR1?

data WORK.want;
  set WORK.Test;
  BY var1 DESCENDING var2  ;
  if first.var2 then n+1;
run;


来源:https://stackoverflow.com/questions/61484125/how-do-you-add-a-row-number-in-sas-by-multiple-groups-with-one-variable-in-decen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!