0
votes

I have a large SAS dataset raw_data which contains data collected from various countries. This dataset has a column "country" which lists the country from which the observation is originated. I would like to export a separate .csv file for each country in raw_data. I use the following data step to produce the output:

data _null_;
  set raw_data;
  length fv $ 200;
  fv = "/directory/" || strip(put(country,$32.)) || ".csv";
  file write filevar=fv dsd dlm=',';
  put (_all_) (:);
run;

However, the resulting .csv files no longer have the column names from raw_data. I have over a hundred columns in my dataset, so listing all of the column names is prohibitive. Can anyone provide me some guidance on how I can modify the above code so as to attach the column names to the .csv files being exported? Any help is appreciated!

2

2 Answers

1
votes

You can create a macro variable that holds the variable names and puts them to the CSV file.

proc sql noprint;
select name into :var_list separated by ", "
from sashelp.vcolumn
where libname="WORK" and memname='RAW_DATA'
order by varnum;
quit;

data _null_;
set raw_data;
length fv $ 200;
by country;
fv = "/directory/" || strip(put(country,$32.)) || ".csv";

if first.country then do;
    put "&var_list";
end;

file write filevar=fv dsd dlm=',';
put (_all_) (:);
run;
1
votes

Consider this data step that is very similar to your program. It uses VNEXT to query the PDV and write the variable names as the first record of each file.

proc sort data=sashelp.class out=class;
   by age;
   run;
data _null_;
   set class;
   by age;
   filevar=catx('\','C:\Users\name\Documents',catx('.',age,'csv'));
   file dummy filevar=filevar ls=256 dsd;
   if first.age then link names;
   put (_all_)(:);
   return;
names:
   length _name_ $32;
   call missing(_name_);
   do while(1);
      call vnext(_name_);
     if _name_ eq: 'FIRST.' then leave;
      put _name_ @;
     end;
   put; 
   run;