DATA Step, Macro, Functions and more

What's wrong with codes?

Reply
Contributor
Posts: 49

What's wrong with codes?

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;

Super User
Posts: 5,260

Re: What's wrong with codes?

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).

Data never sleeps
Super Contributor
Posts: 333

Re: What's wrong with codes?

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

Super Contributor
Posts: 358

Re: What's wrong with codes?

Also a RETAIN MYLABEL;  ??

Respected Advisor
Posts: 3,777

Re: What's wrong with codes?

OS2Rules wrote:

Also a RETAIN MYLABEL;  ??

Would you? Did you test?

What does "sum" statement imply?

Super User
Posts: 5,260

Re: What's wrong with codes?

No need, RETAIN is implied within the var + n; construct.

Data never sleeps
Valued Guide
Posts: 3,208

Re: What's wrong with codes?

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. 

---->-- ja karman --<-----
Ask a Question
Discussion stats
  • 6 replies
  • 235 views
  • 0 likes
  • 6 in conversation