DATA Step, Macro, Functions and more

Lag function and _n_

Reply
Regular Contributor
Posts: 216

Lag function and _n_

Hi Everyone

I am using the below data step to set my tprfiled variable to the prior value for it except for the first record in the data set. However, it is not recognizing the first record's 0 when processing the second record--a null is inserted instead of 0. Any ideas why this is?

Paul

data s1astpr3;

set s1astpr2;

if _n_ ne 1 then tprfiled=lag(tprfiled);

run;

entity_idtprfiled
10
2
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
201
211
220
Frequent Contributor
Posts: 106

Re: Lag function and _n_

Hi,

Try with just -> tprfiled=lag(tprfiled);  it will give null value for first row and lag values for subsequent rows.

your code is giving the same value for tprfiled which must be 0 in your source data, and lagging null value to second row.

Regular Contributor
Posts: 216

Re: Lag function and _n_

I tried doing just doing just the lag initially, but wanted to accommodate the issue with the first record. But I just tried the below, which is a variation of this and it works:

data s1astpr3;

set s1astpr2;

tprfiled2=tprfiled;

tprfiled=lag(tprfiled);

if _n_ = 1 then do;

tprfiled=tprfiled2;

end;

drop tprfiled2;

run;

Super User
Super User
Posts: 7,401

Re: Lag function and _n_

Hi,

Not sure about lag, tried using it myself some time back and had some weird results.  So this doesn't answer your question, but does do whats requested:

proc sql;

  create table WANT as

  select  A.ENTITY_ID,

          B.TPRFILED

  from    HAVE A

  left join HAVE B

  on      A.ENTITY_ID=(B.ENTITY_ID+1);

quit;

Regular Contributor
Posts: 216

Re: Lag function and _n_

Hi Rw9

The only issue with this is that I have a lot more columns that I indicated and they change regularly, so I don't really want to deal with proc sql and writing out column names.

Paul

Ask a Question
Discussion stats
  • 4 replies
  • 257 views
  • 3 likes
  • 3 in conversation