I'm trying to create a new column that counts the number of practice sessions between each optional practice session, but I want it to reset the counts between each two optional sessions and not aggregate. How can I do this? I know how to count it by aggregating the observations, but not how to reset them between each optional session.
data have; input ID $Practice; datalines;
1 Mandatory
2 Mandatory
3 Optional
4 Optional
5 Mandatory
6 Mandatory
7 Mandatory
8 Mandatory
9 Optional
10 Mandatory
11 Mandatory
12 Optional
I basically want a dataset that looks like this
ID Practice Count
1 Mandatory 1
2 Mandatory 2
3 Optional 2
4 Optional 0
5 Mandatory 1
6 Mandatory 2
7 Mandatory 3
8 Mandatory 4
9 Optional 4
10 Mandatory 1
11 Mandatory 2
12 Optional 2
You want to:
data want;
set have;
if lag(practice)='Optional' then count=0;
count+(practice^='Optional');
run;
v
You want to:
data want;
set have;
if lag(practice)='Optional' then count=0;
count+(practice^='Optional');
run;
v
Hi V,
Your code didn't work. When I tried to use it, it gave me "." for most of the mandatory cells and then "0" for the mandatory rows that comes right after the optional rows instead. I checked my log as well and there were no error messages so I'm not sure what went wrong.
Please disregard this, it worked.
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.