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!
| ID | Visit | Var | CumVar |
| 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 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;
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;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
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.