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

Suppose I have a SAS table as follows:

 

ID   Yr

A    2003

A    2004

A    2004

B    2003

B    2003

 

I would like to add a new column which has the number of occurrences of each ID as follows:

 

ID   Yr       Occurences

A    2003   3

A    2004   3

A    2004   3

B    2003   2

B    2003   2

 

Please advise on how I can do this

1 ACCEPTED SOLUTION

Accepted Solutions
novinosrin
Tourmaline | Level 20


data have;
input ID $   Yr;
cards;
A    2003

A    2004

A    2004

B    2003

B    2003
;

proc sql;
 create table want as
 select *, count(*) as occurences
 from have
 group by id
 order by id, yr;
quit;

View solution in original post

3 REPLIES 3
novinosrin
Tourmaline | Level 20


data have;
input ID $   Yr;
cards;
A    2003

A    2004

A    2004

B    2003

B    2003
;

proc sql;
 create table want as
 select *, count(*) as occurences
 from have
 group by id
 order by id, yr;
quit;
novinosrin
Tourmaline | Level 20
data want;
 do _n_=1 by 1 until(last.id);
  set have;
  by id;
  occurences=sum(occurences,1);
 end;
 do _n_=1 to _n_;
  set have;
  output;
 end;
run;
aalluru
Obsidian | Level 7

That worked perfectly. Thank you so much!

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
  • 3 replies
  • 1876 views
  • 0 likes
  • 2 in conversation