Count Observations by Group in SAS?

In SAS, count observations by group is a process which involves the use of the proc sql statement to count the number of rows within a data set for each distinct value of a certain group variable. This allows the analyst to calculate how many observations are in each group, which can be useful for summarizing data for further analysis.


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;

  • 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.

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

x