Hi all, I want to export multiple csv files (by gender) from one sas dataset. My code below works to create the files, however I can't figure out how to keep the column names in the exported files. Please help!
Note: I am using the sashelp.class dataset for my code below
data _null_; set class; length fv $ 200; fv = "C:\Users\abi\Desktop\Output" || TRIM(put(sex,4.)) || ".csv"; file write filevar=fv dsd dlm=',' lrecl=32000; put (_all_) (:);; run;
Is the source data sorted by the variable used to split?
If so use BY group processing to decide when to write the header row.
%let path=%sysfunc(pathname(work));
proc sort data=sashelp.class out=class;
by sex;
run;
data _null_;
set class;
by sex ;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd ;
if first.sex then put "NAME,SEX,AGE,HEIGHT,WEIGHT";
put (_all_) (+0);
run;
Otherwise create the files with the header rows first then use the MOD option on the FILE statement in your step that writes the data lines.
proc contents data=class noprint out=names(keep=varnum name label);
run;
proc sql;
create tables headers as
select distinct a.*,cats("&path/",b.sex,'.csv') as fv
from names a
, class b
order by fv, varnum
;
quit;
data _null_;
set headers;
file out dsd filevar=fv ;
put name @ ;
run;
data _null_;
set class;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd mod;
put (_all_) (+0);
run;
Is the source data sorted by the variable used to split?
If so use BY group processing to decide when to write the header row.
%let path=%sysfunc(pathname(work));
proc sort data=sashelp.class out=class;
by sex;
run;
data _null_;
set class;
by sex ;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd ;
if first.sex then put "NAME,SEX,AGE,HEIGHT,WEIGHT";
put (_all_) (+0);
run;
Otherwise create the files with the header rows first then use the MOD option on the FILE statement in your step that writes the data lines.
proc contents data=class noprint out=names(keep=varnum name label);
run;
proc sql;
create tables headers as
select distinct a.*,cats("&path/",b.sex,'.csv') as fv
from names a
, class b
order by fv, varnum
;
quit;
data _null_;
set headers;
file out dsd filevar=fv ;
put name @ ;
run;
data _null_;
set class;
fv=cats("&path/",sex,'.csv');
file csv filevar=fv dsd mod;
put (_all_) (+0);
run;
April 27 – 30 | Gaylord Texan | Grapevine, Texas
Walk in ready to learn. Walk out ready to deliver. This is the data and AI conference you can't afford to miss.
Register now and lock in 2025 pricing—just $495!
Still thinking about your presentation idea? The submission deadline has been extended to Friday, Nov. 14, at 11:59 p.m. ET.
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.
Ready to level-up your skills? Choose your own adventure.