Hi guys,
i have a data problem where i have to select out group of observation until certian condition is met ( until i have find flag=1). here is the sample datset:
data have;
input id flag;
cards;
001 0
001 0
001 0
001 1
001 0
001 0
002 0
002 1
002 0
;
run;
data want;
input id flag;
cards;
001 0
001 0
001 0
001 1
002 0
002 1
;
run;
i was trying to use do loop , but seems like i am doing something wrong:
here is my try:
data want;
do until(last.id);
set have;
by id;
do _n_=1 to (f<=1);
if f<=1;
end;
output;
end;
stop;
run;
but it's not working. Any help is highly appreciated
Hi
LAST.ID will be set to 1 as soon as the end of the first group is reached, so this is why, you only see one group.
Find below a code sample, that will do what you need. It is based on the SUM statement.
data want2;
set have;
by id;
if first.id = 1 then do;
flagCount = 0;
end;
flagCount + (flagCount + flag);
if flagCount <= 1;
run;
Bruno
Hi,
Something like:
data want (drop=op); set have; by id; retain op; if first.id then op=1; if op=1 then output; if flag=1 then op=0; run;
Hi
LAST.ID will be set to 1 as soon as the end of the first group is reached, so this is why, you only see one group.
Find below a code sample, that will do what you need. It is based on the SUM statement.
data want2;
set have;
by id;
if first.id = 1 then do;
flagCount = 0;
end;
flagCount + (flagCount + flag);
if flagCount <= 1;
run;
Bruno
@BrunoMueller Hi Bruno, Thanks for the solution, but what if i need like this
data have;
infile cards missover;
input id flag switch $8.;
cards;
001 0
001 0
001 0
001 1 first
001 0
001 0
001 1 second
001 0
001 0
002 0
002 1 first
002 0
002 0
002 1 second
002 1 third
;
run;
/*I need three outputs based on switches i,e.*/
/**/
/*data first will looks like:*/
data first;
input id flag switch $8.;
cards;
001 0
001 0
001 0
001 1 first
002 0
002 1 first
;
run;
/*this is selecting observation from first to second*/
data second;
input id flag switch $8.;
cards;
001 1 first
001 0
001 0
001 1 second
002 1 first
002 0
002 0
002 1 second
;
run;
data third;
input id flag switch $8.;
cards;
002 1 second
002 1 third
;
run;
please help!
hi
You need to change the logic for this line
flagCount + (flagCount + flag);
so that you get the right setting.
For instance
flagCount + (flagCount + (switch = "first"));
will only write the observation til you reach switch = "first"
Bruno
@SASFREAK: A DOW loop approach (do until(last. ...); set ...) was suggested for a very similar question in this recent thread.
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!
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.