SAS: convert character to numeric without creating another variable

I want to convert x to numeric.

 DATA test; input x $1.; cards; 1 2 0 ; run; 

I tried different ways:

  • C *1 :

     /* trial1 */ DATA test1; SET test; x = x*1; run; 

The following note is printed in the journal:

 NOTE: Character values have been converted to numeric values at the places given by: (Line):(Column). 2470:3 NOTE: Numeric values have been converted to character values at the places given by: (Line):(Column). 2470:4 

And the format does not change.

  • With input() :

     /* trial2 */ DATA test2; SET test; x = input(x,BEST1.); run;` 

The following note is printed in the journal:

 NOTE: Numeric values have been converted to character values at the places given by: (Line):(Column). 2396:3 

And the format does not change.

  • With informat :

     /* trial3 */ DATA test3; SET test; informat x BEST1.; run; 

The following error is printed in the log:

 ERROR 48-59: The informat $BEST was not found or could not be loaded. 

What is explained here and here : the compiler detects different types of variables and format, makes a mistake, adds the alleged missing $ and therefore does not find the format.

All these tests will work if I created a second variable, for example, for example:

 DATA test4; SET test (rename=(x=x2)); x = x2*1; drop x2; run; 

But I'm trying to clear my code, and I wonder if there is a way to do such a conversion without this?

+7
type-conversion sas
source share
2 answers

As mentioned elsewhere, you need to use a second variable. SAS will not allow you to directly change the type of a column variable, but you can spoof things using renaming similarly above.

The only thing I propose to distinguish from NEOmen or higher is using input . The length / purpose or method *1 both good, but they rely on an automatic SAS type conversion that will add a note to your journal about its execution. You should avoid such things in your journal, as they are messy and make others think that you might have done so in the event of an accident.

Using the NEOmen Test Dataset:

 data test1; set test(rename=x=x_old); x=input(x_old,best12.); *whatever is appropriate informat for your variable; run; 
+7
source share

Once a variable is defined as numeric or character, you cannot change its data type, perhaps you can use a workaround below.

 DATA test; input x $1.; cards; 1 2 0 ; run; data test1(drop=x_old); length x 8.; set test(rename = (x=x_old)); x=x_old; run; 
+4
source share

All Articles