how to convert a variable with both character and numeric variable into a numeric variable in sas

StackOverflow https://stackoverflow.com/questions/23633579

  •  21-07-2023
  •  | 
  •  

Pregunta

i looked at the previous links related to the topic and tried using the commands but it is showing error. i have a variable var1 = census tract 244.1 which is in character format of length 25. i need a final variable which will contain only the number 244.1 and the format should be numeric

i used the following commands: newvar = input (var1, 8.) but it showed error mentioning it as an invalid argument to function INPUT.

i also used: newvar = input (var1, best32.) but again the same error message as above.

i tried to remove the word 'census tract' word using: TRACT =tranwrd(var1, "Census Tract", ''); the message said that var1 is defined both as character and numeric variable

i have run out of option. so need help. i'm using sas 9.3

¿Fue útil?

Solución

You'll have to do this in two steps:

Extract the characters "244.1"

Since we're only interested in 244.1, we'll get rid of the rest. This could have been done in a number of ways, one of which is tranwrd as you pointed out.

var2 = substr(var1, 13, 6);

Convert the character value "244.1" to the number 244.1

We need to take the character value and convert to a number. The input function allows us to take a character value and convert it to a number using an informat. An informat is just a way of telling sas how to interpret the value. In this case, treat it as a number stored in 8 bytes.

var3 = input(var2, 8.); 

Full example program:

data work.one;

   var1 = "census tract 244.1";
   var2 = substr(var1, 13, 6);
   var3 = input(var2, 8.);

run;

/* Show that var3 is a numeric variable */
proc contents data=work.one;
run;

Bonus Info

Note that you cannot save the converted value back to the original "var1" variable, since once it has been declared as a character variable it cannot store a number. If you did want to keep the same variable you would have to drop var1, then rename var3 to var1:

drop var1;
rename var3=var1;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top