Let's say I have a data below:
data have;
infile cards truncover;
input ID :$4.;
cards;
0196
0196
0196
0395
0752
1277
1277
;
run;
What I want is to have a new table with a new column wherein it will count the number of times the ID appeared but not group it. To explain it clearer, I want to have an output like this:
ID Count_ID
0196 1
0196 2
0196 3
0395 1
0752 1
1277 1
1277 2
Could someone help me on this? A program that will work even if ID is not sort by order
Hi @iSAS For unsorted count, Hash is easy and convenient. While the sorted and Hash solutions have already been posted, I was thinking what if your ID are all digits and do have any alpha char. If this is true, key indexing is very viable and yet another convenient solution
data have;
infile cards truncover;
input ID :$4.;
cards;
0196
0196
0196
0395
0752
1277
1277
;
run;
data want;
do until(z);
set have end=z;
array t(999999)_temporary_;
_n_=input(id,32.);
if t(_n_) then t(_n_)=sum(t(_n_),1);
else t(_n_)=1;
count_id=t(_n_);
output;
end;
run;
Data want;
Set Have;
Count_ID + 1;
By ID;
if first.ID then Count_ID = 1;
Run;
As requested, this works regardless of the sort order
data want;
if _N_=1 then do;
declare hash h();
h.definekey('id');
h.definedata('Count_ID');
h.definedone();
end;
set have;
if h.find() ne 0 then Count_ID = 1;
else Count_ID + 1;
h.replace();
run;
Result:
ID Count_ID 0196 1 0196 2 0196 3 0395 1 0752 1 1277 1 1277 2
Hi @iSAS For unsorted count, Hash is easy and convenient. While the sorted and Hash solutions have already been posted, I was thinking what if your ID are all digits and do have any alpha char. If this is true, key indexing is very viable and yet another convenient solution
data have;
infile cards truncover;
input ID :$4.;
cards;
0196
0196
0196
0395
0752
1277
1277
;
run;
data want;
do until(z);
set have end=z;
array t(999999)_temporary_;
_n_=input(id,32.);
if t(_n_) then t(_n_)=sum(t(_n_),1);
else t(_n_)=1;
count_id=t(_n_);
output;
end;
run;
Good news: We've extended SAS Hackathon registration until Sept. 12, so you still have time to be part of our biggest event yet – our five-year anniversary!
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.