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
Rhodochrosite | Level 12

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-2024.png

Available on demand!

Missed SAS Innovate Las Vegas? Watch all the action for free! View the keynotes, general sessions and 22 breakouts on demand.

 

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