Hi Guys,
I want to rank my my data within groups, so I used lag function in my codes. But it seems this function does not work. I'm wondering why lag1(mylabel) is missing when _n_=2. Anyone could help me out? Thanks.
Mike
data cake;
input Name $ 1-10 type 12-13 Taste 15-16;
datalines;
Davis 1 84
Orlando 1 80
Ramey 1 72
Roe 2 75
Sanders 2 79
Simms 2 77
Strickland 2 79
;run;
proc sort data=cake;
by type taste;run;
data a;
set cake;
by type taste;
if type=lag1(type) then mylabel=1+lag1(mylabel);
else mylabel=1;
if _n_=1 then mylabel=1;
run;
Haven't investigated your lag-problem, but I am generally more convenient using first./last.logic, which I believe you could use together wit a conditional mylabel+1; (which will make mylabel automatically retained).
I dont think you can recursively create a variable with the lag function because the variable being created is going into the output dataset and not available to SAS PDV (I admit, I may have the SAS workings wrong here ... someone feel free to correct this).
Why do you not want to use something like the following as suggested?
data a;
set cake;
by type taste;
if first.type then mylabel=1;
else mylabel + 1;
run;
EJ
Also a RETAIN MYLABEL; ??
OS2Rules wrote:
Also a RETAIN MYLABEL; ??
Would you? Did you test?
What does "sum" statement imply?
No need, RETAIN is implied within the var + n; construct.
The construction with conditions and using lag in it is confusing
The LAG function is a logical queue construct pushing the current value in and getting the oldest out of it. It is not the same as a retain.
SAS(R) 9.4 Functions and CALL Routines: Reference (LAG)
At the first time " mylabel=1+lag1(mylabel); " is called (_n_ =2) it will push a missing in the que as mylabel for that observation has not been defined. It is exactly working as has been described.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.