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
seq | los | laglos |
---|---|---|
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 |
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
laglos=ifn(seq eq 1,los,lag(los));
laglos=ifn(seq eq 1,los,lag(los));
Glad to know you are here, DN. I have always wanted to ask, why lag() changes behavior when inside ifn()?
Thanks,
Haikuo
Haikuo: take a look at: http://www.sascommunity.org/wiki/Conditional_Use_of_LAG
Thanks, Art. Now I understand that inside ifn() or ifc(), the lag() is always called.
Haikuo
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;
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
Thanks so much for all of you guys!
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
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.