120 likes | 327 Views
Combining Data Sets with Character Variables of Different Lengths Martha Cox Cancer Outcomes Research Program Cancer Care Nova Scotia. The Problem. 2 data sets to combine (SET) They contain some of the same character variables, but with different lengths. How ?.
E N D
Combining Data Sets with Character Variables of Different LengthsMartha CoxCancer Outcomes Research ProgramCancer Care Nova Scotia
The Problem • 2 data sets to combine (SET) • They contain some of the same character variables, but with different lengths.
How ? • PROC APPEND:Uses all attributes from the base data set. • Data step with a SET statement:Manually-created LENGTH statement.
An Easier Solution A macro that creates and then runs a SAS program with the right information.
Algorithm of the Macro • Run PROC CONTENTS for each data set; output the metadata for the character variables. • Merge the results together, keeping both lengths. • Write a SAS program. • Run the SAS program.
%macro union(dsn1=, /*Name of the first data set */ dsn2=, /*Name of the second data set */ out= /*Name of combined data set */); proc contents data=&dsn1 noprint out=out1(keep=name type length where=(type=2)); proc contents data=&dsn2 noprint out=out2(keep=name type length where=(type=2)); run; data _null_; file "combined.sas"; merge out1 out2(rename=(length=length2)) end=last; by name; if _n_ = 1 then put "Data &out;"; l = max(length,length2); put " length " name " $ " l 2. ";"; if last then do; put " set &dsn1 &dsn2;"; put "run;"; end; run; %include "combined.sas"; %mend union;
%macro(dsn1=ONE, dsn2=TWO, out=UNION ); Example: The Call
Contents of Data Set ONE Obs NAME TYPE LENGTH 1 c1 2 4 2 c2 2 8 Contents of Data Set TWO Obs NAME TYPE LENGTH 1 c1 2 3 2 c2 2 10 Example: Input Data Sets
Example: The Program data union; length c1 $ 4; length c2 $ 10; set one two; run;
Example: The Result Contents of Data Set UNION Obs NAME TYPE LENGTH 1 c1 Char 4 2 c2 Char 10
Reference • Authored by Ron Cody, a SAS Books By Users author. • Found in the SAS Sample Library http://support.sas.com/notes/index.html