BookmarkSubscribeRSS Feed
mona4u
Lapis Lazuli | Level 10

 

Hi All, 

Below is an example of what I'm trying to achieve. My goal is to get the variable diff.  

 

X Y LAG DIFF
1 A    
2 A 1 1
3 A 2 1
4 A 3 1
5 A 4 1
1 B    
2 B 1 1
3 B 2 1
4 B 3 1
5 B 4 1

 

Mona 

3 REPLIES 3
Reeza
Super User

Why is the first diff 1 when there's no previous value?
If it's always 1 why is this needed? It would be good to include a use case that illustrates a different scenario.

 

I suspect this is what you're after?

data want;
set have;
by y;
_dif = dif(x);
_lag = lag(x);
if first.y then call missing(_dif, _lag);
run;

@mona4u wrote:

 

Hi All, 

Below is an example of what I'm trying to achieve. My goal is to get the variable diff.  

 

X Y LAG DIFF
1 A    
2 A 1 1
3 A 2 1
4 A 3 1
5 A 4 1
1 B    
2 B 1 1
3 B 2 1
4 B 3 1
5 B 4 1

 

Mona 


 

mona4u
Lapis Lazuli | Level 10

because I don't want to subtract different group values. 

 

the diff value not always 1 this is just dummy 

Reeza
Super User

Did you try the code posted?

I'm assuming groups are defined by Y as you never stated. I'm assuming you want the lag of the variable X, also not specifically stated. 

If the above is true the answer should be correct. Use the DIF/LAG function and reset at the first of each group. 

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 Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 3 replies
  • 225 views
  • 2 likes
  • 2 in conversation