Solved
Contributor
Posts: 21

# Help: Refer previous value in current function (LAG?)

id x

1 2

2 3

3 5

4 8

5 9

6 8

hi, i have sample dataset like above. i want to create a new variable y, such that,

if id = 1, then y = x;

else y(t)= y(t-1) * 2.

in this case:

y(1) = x(1) =  2

y(2) = y(1) *2 = 2*2 = 4

y(3) =y(2) *2 = 4*2 = 8

y(4) =y(3) *2 = 8*2 = 16

y(5) = y(4) *2 = 16*2 = 32

y(6) = y(5) *2 = 32*2 = 64

i am wondering if there is any function to achieve it? looks like lag can't do it.

thanks a lot for your help!

Accepted Solutions
Solution
‎10-14-2012 11:23 PM
Contributor
Posts: 69

## Re: Help: Refer previous value in current function (LAG?)

Hi, you can try this method. You are right, LAG function can't do it.

data test;

input id x;

retain temp;

if id=1 then do;

y=x;

temp=y;

end;

if id ne 1 then do;

y=temp*2;

temp=y;

end;

drop temp;

cards;

1 2

2 3

3 5

4 8

5 9

6 8

;

run;

All Replies
Solution
‎10-14-2012 11:23 PM
Contributor
Posts: 69

## Re: Help: Refer previous value in current function (LAG?)

Hi, you can try this method. You are right, LAG function can't do it.

data test;

input id x;

retain temp;

if id=1 then do;

y=x;

temp=y;

end;

if id ne 1 then do;

y=temp*2;

temp=y;

end;

drop temp;

cards;

1 2

2 3

3 5

4 8

5 9

6 8

;

run;

Contributor
Posts: 21

## Re: Help: Refer previous value in current function (LAG?)

Smart! thank you!

Regular Contributor
Posts: 151

## Re: Help: Refer previous value in current function (LAG?)

You can simplify the code a bit.

data test;

input id x;

retain y;

y=ifn(id=1,x,y*2);

cards;

1 2

2 3

3 5

4 8

5 9

6 8

;

run;

Contributor
Posts: 21

## Re: Help: Refer previous value in current function (LAG?)

Thanks Keith, works better!

Contributor
Posts: 69

## Re: Help: Refer previous value in current function (LAG?)

Year, this is easier.

🔒 This topic is solved and locked.