BookmarkSubscribeRSS Feed

Ready to add codelists by group as a new utility?

Started ‎09-19-2023 by
Modified ‎09-19-2023 by
Views 1,166

Sunil 1.png

 

Instead of always using PROC FREQ to list unique values by a group variable, why not try using the DATA STEP as an alternative?  The DATA STEP is one the most powerful SAS procedures that enables conditional and group processing, along with statements and functions. With the BY statement, FIRST. and LAST. conditions can be applied to create and update variables.  The RETAIN statement preserves the unique values and the CATX() function concatenates all unique values.  When the LAST.group record is reached, then the record is saved so that the dataset contains unique records by group variable.

 

Often programmers find one variable containing a list of unique values easier to review and process instead of PROC FREQ's default rows for each unique value.  In addition, as extra benefits, the unique values can be sorted alphabetically and a count variable can also be added.  Savvy SAS programmers can find multiple applications for this new utility.

 

* create dataset of unique values by sex;
proc sql;
create table class as
select unique sex, name, count(name) as count
from sashelp.class group by sex order by sex, name;
quit;

* concatenate names and then output last sex record;
data nameslst;
 retain nameslst;
 length nameslst $200 count 8.;
 set class; 
 by sex;
 if first.sex then nameslst= "";
 if name > '' then nameslst=catx(', ', strip(nameslst), strip(name));
 if last.sex then do;
  output; 
 end;
 keep sex nameslst count;
run;
 
title 'Codelist by Sex Group';
proc print data=nameslst;
 var sex count nameslst;
run;

 

Version history
Last update:
‎09-19-2023 02:07 PM
Updated by:
Contributors

SAS Innovate 2025: Call for Content

Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!

Submit your idea!

Free course: Data Literacy Essentials

Data Literacy is for all, even absolute beginners. Jump on board with this free e-learning  and boost your career prospects.

Get Started

Article Tags