DATA Step, Macro, Functions and more

counting observations in by group

Regular Contributor
Posts: 244

counting observations in by group

Hi All,

I want to know how many times a by group occured in a table and write that on a separate dataset (has to be a character number as I am concatenating with character as well). Can someone help please.


data have;
input Student_ID $ Course_ID $ Score;
M101 Eng 20
M101 Bio 20
M101 Eng 10
M101 Math 18
F103 Bio 18
F103 Math 99
F103 Eng 16
F103 Che 15
F103 Math 20
F103 Phy 17


DATA want;
line='Totalcount'||Number of M101 by group occurance in have table||Number of F103 by group occurance in have table;


Expected output:


Super User
Posts: 6,752

Re: counting observations in by group

Probably many ways to skin this cat ...


data want;

length line $ 16;

retain line 'Totalcount';


do until (last.Student_ID);

   set have end=done;

   by Student_ID;

   count + 1;


line = cats(line, put(count, z3.));

keep line;

if done;



It's untested, but definitely headed in the right direction.


Are you sure you don't want to keep Student_ID as part of the output line?

Regular Contributor
Posts: 244

Re: counting observations in by group

Posted in reply to Astounding
Hi Astounding,
Thanks for your reply. Your code is working, but I want to put that 2 count in between other character variable. Like:


Expected Output: ABCDM4U004006AAAAAA

Can you please tell me how it is possible. Thanks.
Super User
Posts: 23,667

Re: counting observations in by group

That doesn't make sense, how would you parse the numbers back out.


Wouldn't you at least want a delimiter between the counts? Or a standard format, ie 8 digits?


Are you assuming the Z3 format, so no counts greater than 999?

Super User
Posts: 13,502

Re: counting observations in by group

What happens if you have more than two values for student_id such as M101 M102 M103 F101 F102 and F103?

Ask a Question
Discussion stats
  • 4 replies
  • 4 in conversation