BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
cmemtsa
Quartz | Level 8
data T;
input ID L EXP;
Datalines;
1 1 10
1 2 20
1 4 20
1 5 20 2 1 10 2 2 60 3 2 50 3 3 50 ; data want; do until(last.id); set T; by id; if l<=1 then flag=1; end; do until(last.id); set T; by id; if not flag then exp=0; output; end; drop flag; run;

Hi,

 

with this code, this is the correct output (per ID if First.ID and L>1 all the sequential Exp updated to 0)

1 1 10
1 2 20
1 4 20

1 5 20
2 1 10
2 2 60
3 2 0
3 3 0

 

How can this code be amended in order if per ID the sequence of L is broken, the rest Exp to update to 0? So the output should be:

 

1 1 10
1 2 20
1 4 0

1 5 0
2 1 10
2 2 60
3 2 0
3 3 0

 

Thanks.

1 ACCEPTED SOLUTION

Accepted Solutions
Kurt_Bremser
Super User

Manipulate flag in the second DO loop if the condition is met:

data want;
do until (last.id);
  set T;
  by id;
  if l <= 1 then flag = 1;
end;
put flag=;
do until(last.id);
  set T;
  by id;
  if not first.id and lag(l) ne l - 1 then flag = 0;
  if not flag then exp = 0;
  output;
end;
drop flag;
run;

View solution in original post

6 REPLIES 6
Kurt_Bremser
Super User

Manipulate flag in the second DO loop if the condition is met:

data want;
do until (last.id);
  set T;
  by id;
  if l <= 1 then flag = 1;
end;
put flag=;
do until(last.id);
  set T;
  by id;
  if not first.id and lag(l) ne l - 1 then flag = 0;
  if not flag then exp = 0;
  output;
end;
drop flag;
run;
cmemtsa
Quartz | Level 8

It works. Thank you!

yabwon
Amethyst | Level 16

one other option would be:

data T;
input ID L EXP;
Datalines;
1 1 10
1 2 20
1 4 20
1 5 20
2 1 10
2 2 60
3 2 50
3 3 50
;
run;

data want;
  set T;
  by id;
  dif_L = dif(L);

  if first.ID then 
    do; 
      _tmp_EXP = .;
      if 1 ne L then _tmp_EXP + 0; 
    end;
  else if dif_L ne 1 then 
         do; 
           _tmp_EXP + 0; 
         end;
  
  if _tmp_EXP = 0 then EXP = 0;

  drop _tmp_EXP dif_L;
run;

Bart

_______________
Polish SAS Users Group: www.polsug.com and communities.sas.com/polsug

"SAS Packages: the way to share" at SGF2020 Proceedings (the latest version), GitHub Repository, and YouTube Video.
Hands-on-Workshop: "Share your code with SAS Packages"
"My First SAS Package: A How-To" at SGF2021 Proceedings

SAS Ballot Ideas: one: SPF in SAS, two, and three
SAS Documentation



cmemtsa
Quartz | Level 8

This works too. Thanks!

Ksharp
Super User
data T;
input ID L EXP;
Datalines;
1 1 10
1 2 20
1 4 20
1 5 20
2 1 10
2 2 60
3 2 50
3 3 50
;
data tt;
 set t;
 by id;
 if first.id or dif(l) ne 1 then group+1;
run;
data want;
 do until(last.group);
  set Tt;
  by group;
  if first.group and l<=1 then flag=1;
 end;

 do until(last.group);
  set Tt;
  by group;
  if not flag then exp=0;
  output;
 end;
 drop flag group;
 run;
cmemtsa
Quartz | Level 8
It works. Thanks.