Need help:)
ID | JAHR | LAGE | tmp | lagenew |
1 | 2006 | 1 | 1 | . |
1 | 2007 | 2 | 2 | 1 |
2 | 2007 | 2 | 2 | . |
2 | 2008 | 2 | 2 | . |
2 | 2009 | 2 | 2 | . |
3 | 2007 | 4 | 4 | . |
3 | 2008 | 5 | 5 | 1 |
3 | 2009 | 5 | 5 | 1 |
4 | 2008 | 1 | 1 | . |
4 | 2009 | 1 | 1 | . |
5 | 2008 | 5 | 5 | . |
5 | 2009 | 5 | 5 | 1 |
5 | 2010 | 4 | 4 | 1 |
6 | 2008 | 3 | 3 | . |
6 | 2009 | 3 | 3 | 1 |
6 | 2010 | 3 | 3 | 1 |
i have a problem with the retain statement. I want to know if a ID changed the variable "LAGE" and if it increase or deacrease. It is working for the few first IDs but then SAS does somthing i don't understand. The following is what i was thinking will work, but it does not.
proc sort
data = Mop.increase;
by id jahr;
run;
data hh;
set Mop.increase;
by id;
retain tmp;
if first.id then tmp = lage;
if tmp > lage then lagenew=2;
if tmp < lage then lagenew=1;
tmp=lage;
run;
thanks for your help:-)
RETAIN doesn't really do anything if the variable you are attempting to retain is being overwritten by reading the next observation.
Here is a method using LAG() instead. Make sure to call the LAG() function on every observation.
data want ;
set have ;
by id jahr ;
lag_lage = lag(lage);
if first.id then lag_lage=lage ;
if lage=lag_lage then want=0;
else if lage > lag_lage then want=1;
else want=2 ;
run;
RETAIN doesn't really do anything if the variable you are attempting to retain is being overwritten by reading the next observation.
Here is a method using LAG() instead. Make sure to call the LAG() function on every observation.
data want ;
set have ;
by id jahr ;
lag_lage = lag(lage);
if first.id then lag_lage=lage ;
if lage=lag_lage then want=0;
else if lage > lag_lage then want=1;
else want=2 ;
run;
Hello @annaxenia,
Good news! I think your understanding of the RETAIN statement and your data step are correct, provided that there is no variable named tmp in dataset Mop.increase. The table you've posted does not seem to be the result of that data step.
Using the first three columns of your table as input data, I obtain:
ID JAHR LAGE tmp lagenew 1 2006 1 1 . 1 2007 2 2 1 2 2007 2 2 . 2 2008 2 2 . 2 2009 2 2 . 3 2007 4 4 . 3 2008 5 5 1 3 2009 5 5 . 4 2008 1 1 . 4 2009 1 1 . 5 2008 5 5 . 5 2009 5 5 . 5 2010 4 4 2 6 2008 3 3 . 6 2009 3 3 . 6 2010 3 3 .
you're right! there was a variable named tmp in dataset Mop.increase i did not notice! Thank you very much. It's working now 🙂
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.