I have this data in SAS:
id | year_mont | sales |
---|---|---|
1 | 202201 | 85.28 |
1 | 202202 | 90.05 |
1 | 202203 | 85.28 |
1 | 0 | 85.28 |
1 | 202205 | 85.28 |
1 | 202206 | 85.28 |
1 | 202207 | 85.28 |
I need to create a rank that increases after zero and decreases before zero, per id, like that:
id | year_mont | sales | rank |
---|---|---|---|
1 | 202201 | 85.28 | -3 |
1 | 202202 | 90.05 | -2 |
1 | 202203 | 85.28 | -1 |
1 | 0 | 85.28 | 0 |
1 | 202205 | 85.28 | 1 |
1 | 202206 | 85.28 | 2 |
1 | 202207 | 85.28 | 3 |
Is it possible to do it in SAS?
You need to know how many observations there are in the group and which one is the zero.
You can use a double DOW loop. The first loop to count the observations and find where the zero is. The second one to generate RANK variable and re-read the data so it can be written out.
data have;
input id year_month sales;
cards;
1 202201 85.28
1 202202 90.05
1 202203 85.28
1 0 85.28
1 202205 85.28
1 202206 85.28
1 202207 85.28
;
data want ;
found=0;
do nobs=1 by 1 until(last.id);
set have;
by id;
if year_month=0 then found=nobs;
end;
do rank=1-found to nobs-found ;
set have;
output;
end;
run;
Results:
year_
Obs found nobs id month sales rank
1 4 7 1 202201 85.28 -3
2 4 7 1 202202 90.05 -2
3 4 7 1 202203 85.28 -1
4 4 7 1 0 85.28 0
5 4 7 1 202205 85.28 1
6 4 7 1 202206 85.28 2
7 4 7 1 202207 85.28 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.