Solved
New Contributor
Posts: 2

# Retain

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;

Accepted Solutions
Solution
2 weeks ago
Super User
Posts: 8,120

## Re: Retain

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;
``````

All Replies
Solution
2 weeks ago
Super User
Posts: 8,120

## Re: Retain

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;
``````
Posts: 1,256

## Re: Retain

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        .```
New Contributor
Posts: 2