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;

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

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
  • 1056 views
  • 1 like
  • 3 in conversation