Hello All,
I have to create a rank column based on 2 column values. The columns in the table are Id and datecounter.
I need to rank based on groups, group by order is id then datecounter.
Below is the example of data have
Id | datecounter |
1 | 1-Jan-22 |
2 | 1-Jan-22 |
2 | 10-Jan-22 |
2 | 5-Feb-22 |
3 | 10-Jan-22 |
3 | 11-Jan-22 |
3 | 11-Jan-22 |
3 | 11-Jan-22 |
4 | 15-Feb-22 |
5 | 15-Feb-22 |
Data want
Id | datecounter | Rank |
1 | 1-Jan-22 | 1 |
2 | 1-Jan-22 | 1 |
2 | 10-Jan-22 | 2 |
2 | 5-Feb-22 | 3 |
3 | 10-Jan-22 | 1 |
3 | 11-Jan-22 | 2 |
3 | 11-Jan-22 | 3 |
3 | 11-Jan-22 | 4 |
4 | 15-Feb-22 | 1 |
5 | 15-Feb-22 | 1 |
Basic approach:
proc sort data=have; by id datecounter; run; data want; set have; retain rank; by id; if first.id then rank=1; else rank+1; run;
Note: this assumes that your dates are actually SAS date values and not some character version.
The sort may not be needed if your data is in order.
Retain keeps the values of a variable across data step boundaries.
When you use a By group then SAS creates automatic variables that indicate whether the current observation is the first or last of a by group and are 1/0 (true/false) valued so can be used in If as shown. Note the dot following the keyword First, or Last, then the variable name without a space.
Personally I would call this an ORDER - sequence determined, not a Rank -size of value involved.
proc rank data=have out=want;
by id;
var datecounter;
ranks rank;
run;
Basic approach:
proc sort data=have; by id datecounter; run; data want; set have; retain rank; by id; if first.id then rank=1; else rank+1; run;
Note: this assumes that your dates are actually SAS date values and not some character version.
The sort may not be needed if your data is in order.
Retain keeps the values of a variable across data step boundaries.
When you use a By group then SAS creates automatic variables that indicate whether the current observation is the first or last of a by group and are 1/0 (true/false) valued so can be used in If as shown. Note the dot following the keyword First, or Last, then the variable name without a space.
Personally I would call this an ORDER - sequence determined, not a Rank -size of value involved.
Available on demand!
Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.