Hi all,
I have a dataset as:
Id.no Number Flag
101 543 0
101 657 0
101 723 1
101 123 0
101 432 0
102 564 0
102 634 1
102 327 0
103 765 0
103 567 0
103 908 0
103 432 1
103 231 0
Can I get the observations upto the first occurrence of flag variable as '1' for each id no? I mean the output dataset as:
Id.no Number Flag
101 543 0
101 657 0
101 723 1
102 564 0
102 634 1
103 765 0
103 567 0
103 908 0
103 432 1
Please help me out for this . Thank you
data have;
input Id_no Number Flag;
cards;
101 543 0
101 657 0
101 723 1
101 123 0
101 432 0
102 564 0
102 634 1
102 327 0
103 765 0
103 567 0
103 908 0
103 432 1
103 231 0
;
data want;
do until(last.id_no);
set have;
by id_no;
if _n_ then output;
if flag then _n_=0;
end;
run;
proc print noobs;run;
Id_no | Number | Flag |
---|---|---|
101 | 543 | 0 |
101 | 657 | 0 |
101 | 723 | 1 |
102 | 564 | 0 |
102 | 634 | 1 |
103 | 765 | 0 |
103 | 567 | 0 |
103 | 908 | 0 |
103 | 432 | 1 |
data want;
set have;
by id;
retain write;
if first.id then write = 1;
if write then output;
if flag then write = 0;
run;
This makes use of the fact that 0 and missing are considered false, and any other non-missing value true.
Please take note that a variable does not "occur". It's either present in a dataset (and therefore the data step that reads it) or not. Values occur.
data have;
input Id_no Number Flag;
cards;
101 543 0
101 657 0
101 723 1
101 123 0
101 432 0
102 564 0
102 634 1
102 327 0
103 765 0
103 567 0
103 908 0
103 432 1
103 231 0
;
data want;
do until(last.id_no);
set have;
by id_no;
if _n_ then output;
if flag then _n_=0;
end;
run;
proc print noobs;run;
Id_no | Number | Flag |
---|---|---|
101 | 543 | 0 |
101 | 657 | 0 |
101 | 723 | 1 |
102 | 564 | 0 |
102 | 634 | 1 |
103 | 765 | 0 |
103 | 567 | 0 |
103 | 908 | 0 |
103 | 432 | 1 |
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.