BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
llt34c
Calcite | Level 5

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.

1 ACCEPTED SOLUTION

Accepted Solutions
Astounding
PROC Star

Yes, that's the right tool.  Use an IF/THEN statement.

View solution in original post

4 REPLIES 4
Astounding
PROC Star

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.

llt34c
Calcite | Level 5

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.

Astounding
PROC Star

Yes, that's the right tool.  Use an IF/THEN statement.

llt34c
Calcite | Level 5

Thank you so much!

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to connect to databases in SAS Viya

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.

Discussion stats
  • 4 replies
  • 1619 views
  • 1 like
  • 2 in conversation