DATA Step, Macro, Functions and more

Output last record

Reply
Contributor
Posts: 32

Output last record

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

PROC Star
Posts: 2,316

Re: Output last record

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 

 

 

PROC Star
Posts: 2,316

Re: Output last record

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;

 

PROC Star
Posts: 253

Re: Output last record

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;

Ask a Question
Discussion stats
  • 3 replies
  • 119 views
  • 1 like
  • 3 in conversation