The program defines a macro named '%split_data'. This macro first uses PROC SQL to create a vertical list of macro variables containing the distinct values of vehicle origin. Then, a %DO loop iterates over this list to dynamically generate DATA steps, filtering and saving the data into separate tables (e.g., cars_Asia, cars_Europe, etc.).
Data Analysis
Type : SASHELP
Use the standard SASHELP.CARS table provided with the SAS installation.
1 Code Block
PROC SQL
Explanation : Extracting unique values from the ORIGIN column into a list of incremental macro variables (:ORIGIN1, :ORIGIN2...). The automatic variable &sqlobs is used to store the total number of origins in &NUM_ORIGINS.
Copied!
proc sql noprint;
select distinct origin into :ORIGIN1-
from sashelp.cars;
%let NUM_ORIGINS = &sqlobs;
quit;
1
PROC SQL noprint;
2
select distinct origin into :ORIGIN1-
3
from sashelp.cars;
4
%let NUM_ORIGINS = &sqlobs;
5
QUIT;
2 Code Block
DATA STEP Data
Explanation : A macro loop iterating from 1 to the number of origins found. It generates a DATA step for each iteration. The use of indirect resolution of macro variables (&&ORIGIN&I) allows for dynamically naming the output table and applying the corresponding WHERE filter.
Copied!
%do i = 1 %to &NUM_ORIGINS;
data cars_&&ORIGIN&I;
set sashelp.cars;
where origin = "&&ORIGIN&I";
run;
%end;
1
%DO i = 1 %to &NUM_ORIGINS;
2
DATA cars_&&ORIGIN&I;
3
SET sashelp.cars;
4
where origin = "&&ORIGIN&I";
5
RUN;
6
%END;
3 Code Block
MACRO CALL
Explanation : Executing the macro to start the cutting process.
Copied!
%split_data;
1
%split_data;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
« Moving from static code to Data-Driven Programming is the hallmark of an advanced SAS developer. The technique shown here—using a vertical macro list to drive a iterative loop—allows your code to adapt automatically to whatever values exist in your source data without manual intervention.
Be cautious with table naming. If your data values (like ORIGIN) contain spaces or characters illegal for SAS dataset names (like "Middle East"), the code data cars_&&ORIGIN&i; will fail. In those cases, wrap the macro reference in %SYSFUNC(COMPRESS()) or %SYSFUNC(TRANSLATE()) to ensure valid, SAS-compliant table names. »
SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. ® indicates USA registration. WeAreCAS is an independent community site and is not affiliated with SAS Institute Inc.
This site uses technical and analytical cookies to improve your experience.
Read more.