I have a dataset in SAS, which contains 20 years of data. I want to export to csv file for each year. Is there any easy way to do it?
Here is what I'm doing for one year now (which is naive):
proc export
data=ds (where=(year=2011)) outfile='ds2011.csv' DBMS=CSV replace;
run;
Thanks a lot!
Non-macro option:
You can use the
file
statement in a data step to write out various types of text or delimited files. Using thefilevar
option allows you to create one file for each value of a variable as is done below.Replace
yourdata
with your dataset andwrite_location
with where you want the file to go.This would be an ideal job for SAS/Macro, which allows text substitution into repeated code. See below for a solution (assuming a date range of 1991-2011, change the
%let
statements to suit your range), with a macro%do
loop, which substitutes the value of &dt. (1991-2011) into the code provided in your question.The macro
The
date_export
macro is defined between the%macro
and%mend
statements. Firstly the date range is defined as two macro variables (this can be omitted and the variables plugged straight into the%do
statement, but is stated here for clarity). The%do
statement starts off a loop, with thedt
macro variable ranging betweenstart_date
andend_date
. This could be rewritten as:and the initial two
%let
statements omitted.The loop runs all code between
%do
and%end
, substituting values ofdt
when it finds&dt.
.Export code
There are a few subtle changes required to ensure the
proc export
runs correctly inside the macro loop,Firstly and most obviously I have substituted the year for
&dt.
which passes the value ofdt
into your code.Note that when placed next to the
.csv
an extra period is required (the first period resolves with thedt
, leaving just the single period andcsv
behind).The single quotes from your question need to be replaced with double-quotes, so that the macro will resolve. Otherwise the resulting file will be called literally 'ds&dt..csv'.
You can turn on the following options in SAS to assist with macro debugging and visualisation, check the SAS documentation for more info:
We have not licensed import and export procedures, so we have to use another approach:
This is little bit complicated, but usable. Each variable contains triplet of informations after @ is position of variable second is name of variable, last is format of variable.