BookmarkSubscribeRSS Feed
🔒 This topic is solved and locked. Need further help from the community? Please sign in and ask a new question.
blackandwhite
Obsidian | Level 7

Hi,

 

I would like to create the variable "CumVar" which adds up a value of 1 each time Var=1 (and also retains the same value until the next time Var is 1).

 

Var is binary (1/0).

 

Please see below an example of what I mean.

 

Thanks very much in advance!

 

 

IDVisitVarCumVar
1100
1200
1300
1411
1501
1612
1713
1814
1904
2100
2200
2300
2400
2511
2612
2702
2813
3111
3201
3312
3402

 

 

 

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20

data have;
input ID	Visit	Var;	
cards;
1	1	0	0
1	2	0	0
1	3	0	0
1	4	1	1
1	5	0	1
1	6	1	2
1	7	1	3
1	8	1	4
1	9	0	4
2	1	0	0
2	2	0	0
2	3	0	0
2	4	0	0
2	5	1	1
2	6	1	2
2	7	0	2
2	8	1	3
3	1	1	1
3	2	0	1
3	3	1	2
3	4	0	2
;

data want;
set have;
by id;
if first.id then cum_var=0;
if var then cum_var+1;
run;

View solution in original post

1 REPLY 1
novinosrin
Tourmaline | Level 20

data have;
input ID	Visit	Var;	
cards;
1	1	0	0
1	2	0	0
1	3	0	0
1	4	1	1
1	5	0	1
1	6	1	2
1	7	1	3
1	8	1	4
1	9	0	4
2	1	0	0
2	2	0	0
2	3	0	0
2	4	0	0
2	5	1	1
2	6	1	2
2	7	0	2
2	8	1	3
3	1	1	1
3	2	0	1
3	3	1	2
3	4	0	2
;

data want;
set have;
by id;
if first.id then cum_var=0;
if var then cum_var+1;
run;

hackathon24-white-horiz.png

The 2025 SAS Hackathon has begun!

It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.

Latest Updates

How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 1 reply
  • 825 views
  • 0 likes
  • 2 in conversation