SAS Code to Extract Unique Values from Character Variables
Here's a detailed breakdown of the SAS code for obtaining unique values from all character variables within a dataset:
/* Create a sample dataset */
data sample;
input name $ gender $ age;
datalines;
John M 25
Mary F 30
David M 40
Susan F 35
;
/* Get the list of character variables */
proc contents data=sample out=contents;
run;
data _null_;
set contents;
if type='char' then call symput('char_vars',trim(name)||' ');
run;
/* Get the unique values of all character variables */
%macro unique_values();
%do i=1 %to %sysfunc(countw(&char_vars));
%let var=%scan(&char_vars,&i);
proc sql;
select distinct &var into :&var separated by ','
from sample;
quit;
%put Unique values of &var: &&&var;
%end;
%mend;
%unique_values();
Explanation:
-
Sample Dataset Creation:
- The code starts by creating a sample dataset named 'sample' with character variables 'name' and 'gender'.
-
Identifying Character Variables:
proc contentsis used to retrieve information about the 'sample' dataset. The output is stored in a dataset named 'contents'.- The
data _null_step iterates through the 'contents' dataset. For each record where 'type' is 'char' (indicating a character variable), the variable name is added to a macro variable named 'char_vars'.
-
Unique Value Extraction Macro:
- The
%macro unique_values()macro is defined to extract distinct values for each character variable. - The macro iterates through each variable in 'char_vars' using a
%doloop. - Inside the loop,
proc sqlis used to select distinct values of the current variable and store them in a macro variable with the same name. The values are separated by commas. - The
%putstatement displays the unique values for each variable.
- The
-
Macro Execution:
- Finally, the
%unique_values()macro is executed, resulting in the extraction and display of unique values from all character variables in the 'sample' dataset.
- Finally, the
This code provides a practical solution for efficiently identifying and extracting unique values from character variables within a SAS dataset. The use of macros allows for a flexible and reusable approach, making it easy to adapt for different datasets with varying character variables.
原文地址: https://www.cveoy.top/t/topic/ovsi 著作权归作者所有。请勿转载和采集!