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
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;
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;
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;
That worked perfectly. Thank you so much!
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.