/*** 
Purpose: Export SAS datasets to csv for import into R   
Author:	Marcel Wolbers
Last modification: 20Jul2009
(minimal adaptations for present study 26Sep2013) 
***/

/***************************************
This is a minimally modified version of the macro originally written by F. Harrell for 
joint usage with R-function sasxport.get in library(Hmisc); i.e. for import of SAS datasets into R.
[original macro at http://biostat.mc.vanderbilt.edu/twiki/pub/Main/Hmisc/exportlib.sas]
     
Usage: Copy all datasets that will be imported into R to the WORK library and then call the macro 
	   (see code at the end of this file for an example). 

Last change: MWo, 23Oct2006
***************************************/

%macro exportlib(/*lib,*/  outdir, tempdir);
%IF %QUOTE(&outdir)=   %THEN %LET outdir=.;
%IF %QUOTE(&tempdir)=  %THEN %LET tempdir=C:/WINDOWS/TEMP;
OPTIONS NOFMTERR;
/* PROC COPY IN=&lib OUT=work;RUN; */
PROC CONTENTS DATA=work._ALL_ NOPRINT
    OUT=_contents_(KEEP=memname memlabel name type label format length
                        nobs);RUN;
PROC EXPORT DATA=_contents_ OUTFILE="&outdir/_contents_.csv" REPLACE;RUN;
DATA _NULL_; SET _contents_; BY MEMNAME;
    FILE "&tempdir/_export_.sas"; RETAIN bk -1;
    if FIRST.MEMNAME & (NOBS > 0) THEN DO;
        PUT "DATA " MEMNAME "; SET " MEMNAME ";FORMAT _NUMERIC_ BEST14.;RUN;";
        PUT "PROC EXPORT DATA=" MEMNAME " OUTFILE=" '"' "&outdir/" 
            MEMNAME +bk ".csv" '" ' "REPLACE;RUN;";
        END;
    RUN;
%INCLUDE "&tempdir/_export_.sas";RUN;
%MEND exportlib;

*Library for SAS datasets;
libname vad 'V:\BIOSTATISTICS\RCT\CN_CNS_HIV\28CN_Tamoxifen_RCT\Data\SASvad'; 

*Get all datasets of interest into work;
proc copy in=vad out=work; 
run; 

*Artificially add a label to one of the datasets; 
*(otherwise sasxport.get crashes in R);
data bl_clinical; set bl_clinical; label PatId="PatId"; run; 

%exportlib(V:\BIOSTATISTICS\RCT\CN_CNS_HIV\28CN_Tamoxifen_RCT\Data\SASvadcsv);
