The LAG function is a powerful tool in the SAS programming toolset. It is also one that has unintentional results. First, lets demonstrate how to use it.
The above will return the last value processed for the price variable. The resulting dataset may look like this.
obs price last_price
1 10 .
2 15 10
3 8 15
4 3 8
5 9 3
Now its misuse. Conditional processing will create unexpected results when incorporated with the lag function. Lag returns the last value processed even if it doesn't appear in the resulting dataset. It is also important to note that you shouldn't use lag if you aren't reading dataset records sequentially.
This function can be handy when calculating moving averages and the like.
The following calculates the sum of the last 5 periods: