Terence Tien
Terence Tien

Reputation: 329

How to use SAS to count the frequency of each observation in a column as in R

I simply want to know the total frequency of each variable as in R table(). Can I do that in SAS?

I have a SAS dataset as following.

data level_score;
infile datalines;
input ID $ Level $ SCORE;
return;
datalines;

    1   A2   0.2
    2   A3   0.8
    3   A4   0.3
    4   A5   0.2
    5   A6   0.2
    6   A3   0.6
    7   A4   0.2
    8   A5   0.6
    9   A6   0.2
;
run;

proc print data=level_score;
run;

I want to use SAS to know the frequency of Level and SCORE as in R table()

For variable 'Level'

A2 A3 A4 A5 A6
 1  2  2  2  2

For variable 'SCORE'

0.2 0.3 0.6 0.8
  5   1   2   1

Upvotes: 2

Views: 19060

Answers (1)

Dominic Comtois
Dominic Comtois

Reputation: 10411

The easiest way is to use proc freq as you found out.

proc freq data=level_score;
  table Level;
run;

There are however several other ways to count frequencies. Here are just two of them.

Showing frequencies using proc sql

proc sql;
  select Level, 
         count(*) as Freq
    from level_score
    group by Level;
quit;

Results:

Level Freq 
   A2    1 
   A3    2 
   A4    2 
   A5    2 
   A6    2 

Show frequencies on the log using a data step

* First we need to sort the data by the variable of interest;
proc sort data=level_score out=Level_sorted;
  by Level;
run;

* Then we use the `by` statement with a retain variable, ;
* here called "count". ;
data _null_;
  set Level_sorted;
  by Level;
  count + 1;
  if last.Level then do;
    put "Frequency for Level " Level ": " count;
    count = 0;
  end;
run;

The log shows:

Frequency for Level A2 : 1
Frequency for Level A3 : 2
Frequency for Level A4 : 2
Frequency for Level A5 : 2
Frequency for Level A6 : 2

The latter example can easily be modified to generate a dataset containing the frequencies:

data Level_freqa;
  set level_sorted;
  by Level;
  count + 1;
  if last.Level then do;
    output;
    count = 0;
  end;
  drop ID SCORE;
run;

Upvotes: 2

Related Questions