BookmarkSubscribeRSS Feed
markc
Obsidian | Level 7

Hello,

 

Is it possible to output all variables of the previous record simply?

 

For example, let's say a condition met like x = lag1(x) then the goal is to output all variables from the previous record as well as the current record.

 

Kind regards,

Mark

3 REPLIES 3
ChrisNZ
Tourmaline | Level 20

You can't easily go back except by using POINT=.

Much better to read ahead,

data HAVE;
   x=1; y=1; output; 
   x=2; y=2; output; 
   x=2; y=3; output;
   x=2; y=4; output;
   x=3; y=5; output;
   x=4; y=6; output;
   x=4; y=7; output;
   x=5; y=8; output;
run; 
data WANT;                                  
  merge HAVE HAVE(firstobs=2 keep=X rename=(X=NEXT_X));      
  if X=NEXT_X then do;
    output; 
    KEEP_NEXT+1;
  end;
  else if KEEP_NEXT then do;
    output;
    KEEP_NEXT=0;
  end;
run;

x y 
2 2 
2 3 
2 4 
4 6 
4 7 

 

 

ChrisNZ
Tourmaline | Level 20

Depending on your needs, this can be coded in the much more compact:


data WANT;                                  
  set HAVE ;      
  by X;
  if not (first.X and last.X) ;
run;

 

s_lassen
Meteorite | Level 14

You can use the second solution suggested by @ChrisNZ even if your data are not sorted, just use the NOTSORTED option on your BY statement:

data WANT;

  set HAVE ;

  by X notsorted;

  if not (first.X and last.X) ;

run;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 3 replies
  • 1529 views
  • 1 like
  • 3 in conversation