BookmarkSubscribeRSS Feed
idaida
Calcite | Level 5

Hi

 

How I can select values after conditions inside multiple groups. 

My data looks like 

 

 

id day timep results flag 
1  1   0     23       
1  1   1     43      X
1  1   2     29                   
1  1   3     14       
2  1   0     17     
2  1   1     32   
2  1   2     54      X
2  1   3     59      

 How can I select values before X or after X inside the same ID. 

 

For example the wanted output would be like this for before X 

 

id day timep results flag 
1  1   0     23  

 and after X the results should be:

 

1  1   2     29                   
1  1   3     14      

for id 1. 

2 REPLIES 2
WarrenKuhfeld
Ammonite | Level 13

Here is one way.

data x; input id day timep results flag $; cards;
1  1   0     23       .
1  1   1     43      X
1  1   2     29      .             
1  1   3     14       .
2  1   0     17     .
2  1   1     32   .
2  1   2     54      X
2  1   3     59  .
; 
proc print;run;

data before;
set x(keep=flag);
if flag = 'X' then do;
   f = _n_ - 1;
   set x point=f;
   output;
   end;
run;
proc print; run;

data after;
set x(keep=flag) nobs=n;
if flag = 'X' and _n_ + 1 le n then do;
   f = _n_ + 1;
   set x point=f;
   output;
   end;
run;
proc print; run;
Ksharp
Super User
data x; 
input id day timep results flag $; 
cards;
1  1   0     23       .
1  1   1     43      X
1  1   2     29      .             
1  1   3     14       .
2  1   0     17     .
2  1   1     32   .
2  1   2     54      X
2  1   3     59  .
; 
run;

data before after;
 set x;
 by id;
 retain found;
 if first.id then call missing(found);
 if flag='X' then found=1;
 if not found then output before;
  else if flag ne 'X' then output after;
  drop found;
run;

sas-innovate-wordmark-2025-midnight.png

Register Today!

Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.


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
  • 2 replies
  • 965 views
  • 0 likes
  • 3 in conversation