Solved
Contributor
Posts: 38

# LAG function and its queue

I learned that the LAG function creates a queue and populates it with a value when called. In the following example, the line "a=Lag(Value);" makes sure that LAG is called for every observation, so the queue should be well populated with the values of variable "Value".

Why is it then that when "b=Lag(Value);" is called for the first time in the second iteration ("IF _n_>=2...") no value is given to variable "b"?

Is it right to assume that there is one queue with values of variable "Value" for variable "a" and another one is initiated when "b=Lag(Value);" is called for variable b?

Data abc;

Input Value :\$5.;

a=Lag(Value);

If _n_>=2 Then b=Lag(Value);

Datalines;

one

two

three

four

Run;

Accepted Solutions
Solution
‎10-12-2013 08:07 PM
Super User
Posts: 8,081

## Re: LAG function and its queue

Yes. Another way to say it is that each occurrence of the LAG() function has its own independent queue of values.  Even when two or more are lagging the same variable.

All Replies
Solution
‎10-12-2013 08:07 PM
Super User
Posts: 8,081

## Re: LAG function and its queue

Yes. Another way to say it is that each occurrence of the LAG() function has its own independent queue of values.  Even when two or more are lagging the same variable.

SAS Super FREQ
Posts: 9,366

## Re: LAG function and its queue

Hi:

This Tech Support note illustrates the correct way to use the LAG function. 24665 - Use the LAG function to conditionally carry information down a data set

The Full code tab in the note shows both the correct and incorrect to call the LAG function.

cynthia

Contributor
Posts: 38