I'm trying to concatenate multiple datasets in SAS, and I'm looking for a way to store information about individual dataset names in the final stacked dataset.
For eg. initial data sets are "my_data_1", "abc" and "xyz", each with columns 'var_1' and 'var_2'.
I want to end up with "final" dataset with columns 'var_1', 'var_2' and 'var_3'. where 'var_3' contains values "my_data_1", "abc" or "xyz" depending on from which dataset a particular row came.
(I have a cludgy solution for doing this i.e. adding table name as an extra variable in all individual datasets. But I have around 100 tables to be stacked and I'm looking for an efficient way to do this.)
The SET statement for concatenating data sets has the following form: SET SAS-data-sets; SAS-data-sets specifies the two or more SAS data sets to concatenate. The observations from the first data set that you name in the SET statement appear first in the new data set.
The first method to combine two tables with the same structure is with the SET statement. First, you use the DATA statement to define the name of the new table. Then, you use the SET statement followed by the names of the tables that you want to append (separate by a whitespace).
If the datasets contain the same variable names, but the formats, labels, and/or lengths are different for any given variable, the new dataset will use the definitions from the dataset listed first in the SET statement.
SAS concatenates data sets (DATA step) and tables (SQL) by reading each row of data to create a new file. To avoid reading all the records, you can append the second file to the first file by using the APPEND procedure: proc append base=year1 data=year2; run; The YEAR1 file will contain all rows from both tables.
If you have SAS 9.2 or newer you have the INDSNAME option http://support.sas.com/kb/34/513.html
So:
data final;
format dsname datasetname $20.; *something equal to or longer than the longest dataset name including the library and dot;
set my_data_1 abc xyc indsname=dsname;
datasetname=dsname;
run;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With