09-09-2016 12:25 PM
I have a large data set that I am trying to use a lag statement that is nested within an if statement. I have attached a file that has the code and also an example of what the output looks like.
The lag statment is returning the previous weight and then using this weight to calculate a difference. The lag statment is nested within an if statement based on animal ID. If the previous ID doesn't match, a "." is returned. It is working with the exception of the 2nd observation. I know the first observation for each animal will be a ".". But the first two are ".". Any help is appreacited.
09-09-2016 12:41 PM
LAG does not retrieve the value from the previous observation. That's a common mistake. LAG retrieves the value from the last time that LAG executed. So it becomes important (in most applications) to make sure that LAG executes on every observation.
The usual fix is to execute LAG on every observation by taking it out of any IF THEN statements. Then on the first observation for each animal ID, reset your new variable (the one that holds the results of the LAG function) to a missing value.
Need further help from the community? Please ask a new question.