Solved
Contributor
Posts: 65

# defining lagged values

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

Accepted Solutions
Solution
‎08-20-2012 06:34 PM
Posts: 3,852

## Re: defining lagged values

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

All Replies
Solution
‎08-20-2012 06:34 PM
Posts: 3,852

## Re: defining lagged values

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

Posts: 3,167

## Re: defining lagged values

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

Thanks,

Haikuo

PROC Star
Posts: 8,164

Posts: 3,167

## Re: defining lagged values

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

Haikuo

Super User
Posts: 6,764

## Re: defining lagged values

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;

Posts: 3,167

## Re: defining lagged values

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

Contributor
Posts: 65

## Re: defining lagged values

Thanks so much for all of you guys!

🔒 This topic is solved and locked.