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.
Thanks.
Yes, that's the right tool. Use an IF/THEN statement.
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.
Thanks for your reply.
I am struggeling on how to reset a variable to a missing value? I have never done this without using some type of if statement.
I appreciate your time.
Yes, that's the right tool. Use an IF/THEN statement.
Thank you so much!
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.
Find more tutorials on the SAS Users YouTube channel.