BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
ANKH1
Pyrite | Level 9

This is the dataset we have:

data have;
input ID age;
datalines;
1	131
1	0
1	0
2	22
2	76
3	0
3 48 3 48 3 3 ; run;

How do you create a variable that counts how many times the variable "age" has appeared up until that age. This means that the same ID can have multiple ages. The output should look like this:

data want;
input ID count_events;
datalines;
a1	131	1
a1	0	2
a1	0	3
b2	22	1
b2	76	2
c4	0	1
c4	48	2
c4	48	3
c4	3	4
;
run;
1 ACCEPTED SOLUTION

Accepted Solutions
Reeza
Super User

That looks like a basic counter.

 

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

Note your want data set does not match the have and is missing a variable. Please ensure you test the code you post.

 


@ANKH1 wrote:

This is the dataset we have:

data have;
input ID age;
datalines;
1	131
1	0
1	0
2	22
2	76
3	0
3 48 3 48 3 3 ; run;

How do you create a variable that counts how many times the variable "age" has appeared up until that age. This means that the same ID can have multiple ages. The output should look like this:

data want;
input ID count_events;
datalines;
a1	131	1
a1	0	2
a1	0	3
b2	22	1
b2	76	2
c4	0	1
c4	48	2
c4	48	3
c4	3	4
;
run;

 

View solution in original post

1 REPLY 1
Reeza
Super User

That looks like a basic counter.

 

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

Note your want data set does not match the have and is missing a variable. Please ensure you test the code you post.

 


@ANKH1 wrote:

This is the dataset we have:

data have;
input ID age;
datalines;
1	131
1	0
1	0
2	22
2	76
3	0
3 48 3 48 3 3 ; run;

How do you create a variable that counts how many times the variable "age" has appeared up until that age. This means that the same ID can have multiple ages. The output should look like this:

data want;
input ID count_events;
datalines;
a1	131	1
a1	0	2
a1	0	3
b2	22	1
b2	76	2
c4	0	1
c4	48	2
c4	48	3
c4	3	4
;
run;

 

sas-innovate-2026-white.png



April 27 – 30 | Gaylord Texan | Grapevine, Texas

Registration is open

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!

Register now

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
  • 774 views
  • 0 likes
  • 2 in conversation