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!
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.