SUPPORT / SAMPLES & SAS NOTES
 

Support

Sample 24694: Obtaining the previous value of a variable within a BY group

DetailsCodeResultsAboutRate It

Bring previous observation's value down to the current observation (lag), resetting at the BY group.

Note:   A LAGn function stores a value in a queue and returns a value stored previously in that queue. Each occurrence of a LAGn function in a program generates its own queue of values.

The queue for LAGn is initialized with n missing values, where n is the length of the queue (for example, a LAG2 queue is initialized with two missing values). When LAGn is executed, the value at the top of the queue is removed and returned, the remaining values are shifted upwards, and the new value of the argument is placed at the bottom of the queue. Hence, missing values are returned for the first n executions of LAGn, after which the lagged values of the argument begin to appear.

Storing values at the bottom of the queue and returning values from the top of the queue occurs ONLY when the function is EXECUTED. A LAGn function that is executed conditionally will store and return values only from the observations for which the condition is satisfied.

Note: This is based upon Example 5.7 from Combining and Modifying SAS Data Sets - Examples.




These sample files and code examples are provided by SAS Institute Inc. "as is" without warranty of any kind, either express or implied, including but not limited to the implied warranties of merchantability and fitness for a particular purpose. Recipients acknowledge and agree that SAS Institute shall not be liable for any damages whatsoever arising out of their use of this material. In addition, SAS Institute will provide no support for the materials contained herein.