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.
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.