How to Count Observations by Group in SAS


You can use the following methods to count the total observations by group in SAS:

Method 1: Count Observations by One Group

proc sql;
    select var1, count(*) as total_count
    from my_data
    group by var1;
quit;

Method 2: Count Observations by Multiple Groups

proc sql;
    select var1, var2, count(*) as total_count
    from my_data
    group by var1, var2;
quit;

The following examples show how to use each method with the following dataset in SAS:

/*create dataset*/
data my_data;
    input team $ position $ points;
    datalines;
A Guard 15
A Guard 12
A Guard 29
A Forward 13
A Forward 9
A Forward 16
B Guard 25
B Guard 20
C Guard 34
C Forward 19
C Forward 3
C Forward 8
;
run;

/*view dataset*/
proc print data=my_data;

Example 1: Count Observations by One Group

The following code shows how to count the total number of observations by team:

/*count observations by team*/
proc sql;
    select team, count(*) as total_count
    from my_data
    group by team;
quit;

From the output we can see that team A contains 6 observations, team B contains 2 observations, and team C contains 4 observations.

Example 2: Count Observations by Multiple Groups

The following code shows how to count the total number of observations, grouped by team and position:

/*count observations by team and position*/
proc sql;
    select team, position, count(*) as total_count
    from my_data
    group by team, position;
quit;

From the output table we can see:

  • A total of 3 players belong on team A and have a position of Forward.
  • A total of 3 players belong on team A and have a position of Guard.
  • A total of 2 players belong on team B and have a position of Guard.
  • A total of 3 players belong on team C and have a position of Forward.
  • A total of 1 player belongs on team A and has a position of Guard.

Additional Resources

The following tutorials explain how to perform other common tasks in SAS:

How to Normalize Data in SAS
How to Rename Variables in SAS
How to Remove Duplicates in SAS
How to Replace Missing Values with Zero in SAS

Leave a Reply

Your email address will not be published. Required fields are marked *