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 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 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
  • 827 views
  • 0 likes
  • 3 in conversation