Create Windows folders using SAS

How to create windows folders using SAS

Suppose, during a SAS project you require to create a large number of reports. Each file is supposed to be saved in different folder and number of files 100+ or  1000+.  What would you do ?
Would you manually create these many folders ... Do you really have so much of time to waste ...
No !... If you respect your time, then don't worry we are here to help you out.

Download the following data for the test case:

Download data for the exercise

Problem statement 

In the file downloaded, we have data for 4 (it can be 100+ in your case) countries and we need to break the data country wise and save the individual file .csv file into country specific folder. Also, you need to create these folders.

Below is the code, that you can use and customize as per your requirement.

/*Define the path where you have placed the data, in my PC path is G:\AA\Sample data */

%Let file_location  = G:\AA\Sample data;

/* Import it */

Proc import datafile = "&file_location.\Sample MKDIR.csv"
out = base_data
dbms = csv replace;
getnames = yes;

/*Count the number of countries - for automation perspective */
Proc Sql;
select count(distinct country) into :n from base_data;

/* Listing countries - for automation perspective */
Proc Sql;
select distinct country  into :list separated by "|" from base_data;

options noxwait;
%Macro Break_export_save;

/* Run loop n times - n is global macro variable = the number of countries*/
%do i = 1 %to &n.;

/* Fetching Country name one by one from list */
%let country = %scan(&list.,&i.,"|");

/*Breaking data*/

Data &country.;
set  base_data;
where country = "&country.";

/*Make folder*/
X Mkdir "&file_location.\&country.";

/*Finally exporting data*/
Proc Export data = &country.
Outfile = "&file_location.\&country.\&country..csv"
dbms = csv replace;



/*Code ends here*/
Why did we use noxwait option ? When we use an X command in SAS, it invokes the command prompt in operating system. We need to manually close it using "Quit" command. Just imagine, if the loop runs for 1000 times and you have to manually close it every time, I am sure that you would get crazy.  So there is no need to get crazy, noxwait option is here to help you out.

Try this and believe me you would love it. You can modify this algorithm for your case.

Enjoy reading our other articles and stay tuned with ...

Kindly do provide your feedback in the 'Comments' Section and share as much as possible.

No comments:

Post a Comment

Do provide us your feedback, it would help us serve your better.