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:

  1. Sample Dataset Creation:

    • The code starts by creating a sample dataset named 'sample' with character variables 'name' and 'gender'.
  2. Identifying Character Variables:

    • proc contents is 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'.
  3. 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 %do loop.
    • Inside the loop, proc sql is 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 %put statement displays the unique values for each variable.
  4. 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.

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.

SAS Code to Extract Unique Values from Character Variables

原文地址: https://www.cveoy.top/t/topic/ovsi 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录