0
votes

I have two datasets, both with same variable names. In one of the datasets two variables have character format, however in the other dataset all variables are numeric. I use the following code to convert numeric variables to character, but the numbers are changing by 490.6 -> 491. How can I do the conversion so that the numbers wouldn't change?

data tst ;
set data (rename=(Day14=Day14_Character Day2=Day2_Character)) ;
Day14 = put(Day14_Character, 8.) ;
Day2 = put(Day2_Character, 8.) ;
 drop Day14_Character Day2_Character ;
 run;
2
What is the length(s) of the character variable(s) you are trying to match?Tom

2 Answers

0
votes

Your posted code is confused. Half of it looks like code to convert from character to numeric and half looks like it is for the other direction.

To convert to character use the PUT() function. Normally you will want to left align the resulting string. You can use the -L modifier on the end of the format specification to left align the value.

So to convert numeric variables DAY14 and DAY2 to character variables of length $8 you could use code like this:

data want ;
  set have (rename=(Day14=Day14_Numeric Day2=Day2_Numeric)) ;
  Day14 = put(Day14_Numeric, best8.-L) ;
  Day2  = put(Day2_Numeric, best8.-L) ;
  drop Day14_Numeric Day2_Numeric ;
run;

Remember you use PUT statement or PUT() function with formats to convert values to text. And you use the INPUT statement or INPUT() function with informats to convert text to values.

0
votes

Change the format to something like Best8.2:

 data tst ;
   set data (rename=(Day14=Day14_Character Day2=Day2_Character)) ;
   Day14 = put(Day14_Character, best8.2) ;
   Day2 = put(Day2_Character, best8.2) ;
   drop Day14_Character Day2_Character ;
 run;

Here is an example:

 data test;
   input r ;
   datalines;
   500.04
   490.6
   ;
 run;

 data test1;
   set test;
   num1 = put(r, 8.2);
 run;

If you do not want to specify the width and number of decimal points you can just use the BEST. informat and SAS will automatically assign the width and decimals based on the input data. However the length of the outcome variable may be large unless you specify it explicitly. This will still retain your numbers as in the original variable.