Good afternoon fellow SAS users and the overall SAS community.
I want to use name as a group, and when week is continuous as a cycle.
A 1
A 2
A 3
A 5
A 6
A 15
A 30
B 1
B 2
B 11
B 12
B 20
B 30
Would anyone have any suggestions about how to tackle this question? Thanks
Hi @yuwentaiwan
Here is an approach to do this:
data have;
input name $ WEEK;
datalines;
A 1
A 2
A 3
A 5
A 6
A 15
A 30
B 1
B 2
B 11
B 12
B 20
B 30
;
run;
data have_cycle;
set have;
by name;
_lag = lag(week);
retain cycle;
if first.name then cycle = 0;
if week > _lag+1 then cycle + 1;
drop _:;
run;
proc sql;
create table want as
select name, count(distinct cycle) as count
from have_cycle
group by name;
run;
My best,
Hi @yuwentaiwan
Here is an approach to do this:
data have;
input name $ WEEK;
datalines;
A 1
A 2
A 3
A 5
A 6
A 15
A 30
B 1
B 2
B 11
B 12
B 20
B 30
;
run;
data have_cycle;
set have;
by name;
_lag = lag(week);
retain cycle;
if first.name then cycle = 0;
if week > _lag+1 then cycle + 1;
drop _:;
run;
proc sql;
create table want as
select name, count(distinct cycle) as count
from have_cycle
group by name;
run;
My best,
thank you!!
Or in a single step:
data want;
do until(last.name);
set have;
by name week;
count=sum(count,dif(week) not in (0,1));
end;
run;
(Assuming that dataset HAVE is sorted by NAME WEEK and the values of WEEK are non-missing integers.)
Very elegant Sir @FreelanceReinh
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.