Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a character variable equal to the formatted value of a numeric variable for arbitrary SAS formats?

Tags:

sas

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.)

like image 422
Simon Nickerson Avatar asked Sep 09 '09 12:09

Simon Nickerson


People also ask

How do I convert character variables to numeric in SAS?

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.

How do you change a character variable to numeric?

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.

How do I change the variable format in SAS?

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.

How do you declare a character variable in SAS?

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.


2 Answers

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.

like image 95
secoskyj Avatar answered Oct 15 '22 07:10

secoskyj


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
*/
like image 27
Chang Chung Avatar answered Oct 15 '22 08:10

Chang Chung