Published on :
Macro MIXED

Extraction of Formatted Distinct Values

This code is also available in: Deutsch Español Français
Awaiting validation
The `%mp_distinctfmtvalues` macro is designed to create a new dataset containing only the distinct and formatted values of a designated variable from a source dataset. It uses SAS© functions to determine the format and type of the variable to apply the appropriate formatting. If no format is specified for a numeric variable, a default numeric format of 32 characters is applied. The process is carried out via a PROC SQL with the `SELECT DISTINCT` statement to ensure value uniqueness.
Data Analysis

Type : MIXED


The source dataset is provided via the `libds` parameter. This can be a standard SASHELP dataset, or any other existing dataset in the SAS environment. The macro does not generate internal data (via DATALINES/CARDS) but operates on pre-existing data.

1 Code Block
MACRO Data
Explanation :
This block defines the `%mp_distinctfmtvalues` macro. It initializes local variables to store the format (`fmt`) and type (`vtype`) of the input variable, using external macros `%mf_getvarformat` and `%mf_getvartype`. Then, a `PROC SQL` is used to create a new dataset (`&outds`). The `SELECT DISTINCT` statement ensures that only unique values are retained. Conditional logic with `%IF/%ELSE` applies the appropriate format to the variable (`&var`): if it's a character without a format, the variable is selected directly; if it's a character with a format, or a numeric with a format, the `PUT` function applies the format. For numerics without a format, `PUT(&var,32.)` is used as the default format. The output variable is named `&outvar` and its length is defined by `&varlen`.
Copied!
1%macro mp_distinctfmtvalues(
2 libds=
3 ,var=
4 ,outvar=formatted_value
5 ,outds=work.mp_distinctfmtvalues
6 ,varlen=2000
7)/*/STORE SOURCE*/;
8 
9 %local fmt vtype;
10 %let fmt=%mf_getvarformat(&libds,&var);
11 %let vtype=%mf_getvartype(&libds,&var);
12 
13 PROC SQL;
14 create TABLE &outds as
15 select distinct
16 %IF &vtype=C & %trim(&fmt)=%str() %THEN %DO;
17 &var
18 %END;
19 %ELSE %IF &vtype=C %THEN %DO;
20 put(&var,&fmt)
21 %END;
22 %ELSE %IF %trim(&fmt)=%str() %THEN %DO;
23 put(&var,32.)
24 %END;
25 %ELSE %DO;
26 put(&var,&fmt)
27 %END;
28 as &outvar LENGTH=&varlen
29 from &libds;
30%mend mp_distinctfmtvalues;
This material is provided "as is" by We Are Cas. There are no warranties, expressed or implied, as to merchantability or fitness for a particular purpose regarding the materials or code contained herein. We Are Cas is not responsible for errors in this material as it now exists or will exist, nor does We Are Cas provide technical support for it.
Copyright Info : Base code: Allan Bowe (mentioned in help comments). Other referenced macros (_version.sas) are copyrighted by Rodney Sparapani (2001-2006) under GNU GPL license and Print_Macro_Parameters.sas is copyrighted © 2022, SAS Institute Inc., under Apache-2.0 license.