BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
issac
Fluorite | Level 6

Hi everyone;

I have two columns in the data, named seq and los and want to define new variables named laglos, which get the same value when seq=1 and when seq>1, I want it to get the value los for previous seq value. For example

seqloslaglos
11414
133
253
375
199
2139
133
155
265
386
498
5119
6411

I try this but it does not work:

data new;

set old;

if seq=1 then laglos=los;

output;

else laglos=lag1(los);

output;

run;

Thanks!

Issac

1 ACCEPTED SOLUTION

Accepted Solutions
data_null__
Jade | Level 19

laglos=ifn(seq eq 1,los,lag(los));

View solution in original post

7 REPLIES 7
data_null__
Jade | Level 19

laglos=ifn(seq eq 1,los,lag(los));

Haikuo
Onyx | Level 15

Glad to know you are here, DN. I have always wanted to ask, why lag() changes behavior when inside ifn()?

Thanks,

Haikuo

Haikuo
Onyx | Level 15

Thanks, Art. Now I understand that inside ifn() or ifc(), the lag() is always called.

Haikuo

Astounding
PROC Star

Good to know.  If for some reason you don't have IFN, you can always make sure LAG gets used every time:

laglos = lag(los);

if seq=1 than laglos = seq;

Haikuo
Onyx | Level 15

Well, another victim of twisted lag(). Lag() is the one function whose function can't be correctly deduced from its name. Here is a way, of course you can also use retain:

data old;

input seq    los    laglos;

cards;

1    14    14

1    3    3

2    5    3

3    7    5

1    9    9

2    13    9

1    3    3

1    5    5

2    6    5

3    8    6

4    9    8

5    11    9

6    4    11

;

data new;

set old;

laglos=ifn(seq=1,los,lag(los));

run;

proc print;run;

Your original code has two unnecessary output statements, and one of them was wrongly inserted between if and else. If you need to do more than one thing, you need to use do-loop.

Haikuo

issac
Fluorite | Level 6

Thanks so much for all of you guys!

sas-innovate-2024.png

Today is the last day to save with the early bird rate! Register today for just $695 - $100 off the standard rate.

 

Plus, pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

Register now!

How to Concatenate Values

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 7 replies
  • 669 views
  • 6 likes
  • 5 in conversation