If I have a numeric variable with a format, is there a way to get the formatted value as a character variable?
e.g. I would like to write something like the following to print 10/06/2009
to the screen but there is no putformatted()
function.
data test;
format i ddmmyy10.;
i = "10JUN2009"d;
run;
data _null_;
set test;
i_formatted = putformatted(i); /* How should I write this? */
put i_formatted;
run;
(Obviously I can write put(i, ddmmyy10.)
, but my code needs to work for whatever format i
happens to have.)
You can use the input() function in SAS to convert a character variable to a numeric variable. This function uses the following basic syntax: numeric_var = input(character_var, comma9.); The following example shows how to use this function in practice.
If you have a character variable that is stored as all characters, you can use encode to convert the character variable to numeric and it will create value labels that have the values that were stored with the character variable.
Or open the column view of the data set in the SAS explorer click on the variable name and modify the format. Or open the tableview of the data set in edit mode, click on the column heading to bring up the variable properties box and change the format.
In SAS, you do not have to declare a variable before assigning a value to it. The variable is automatically declared the first time you specify it in an assignment statement. SAS assigns the variable's type and length based on its first occurrence in the DATA step.
The VVALUE
function formats the variable passed to it using the format associated with the variable. Here's the code using VVALUE
:
data test;
format i ddmmyy10.;
i = "10JUN2009"d;
run;
data _null_;
set test;
i_formatted = vvalue(i);
put i_formatted;
run;
While cmjohns solution is slightly faster than this code, this code is simpler because there are no macros involved.
Use vformat()
function.
/* test data */
data test;
i = "10jun2009"d;
format i ddmmyy10.;
run;
/* print out the value using the associated format */
data _null_;
set test;
i_formatted = putn(i, vformat(i));
put i_formatted=;
run;
/* on log
i_formatted=10/06/2099
*/
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