Help using Base SAS procedures

character string to numeric value conversion

Reply
Contributor
Posts: 32

character string to numeric value conversion

I'm looking for the best method to convert a character string to a numeric value.

For example:

'EAST' should be converted to the number 1
'WEST' should be converted to the number 2
'NORTH' should be converted to the number 3
'SOUTH' should be converted to the number 4

Please let me know if this is not the correct forum.

Please let me know if more info is required.

Thanks
SAS Super FREQ
Posts: 8,861

Re: character string to numeric value conversion

Hi:
Consider this example program that uses the PUT function and the INPUT function to convert the SEX variable from SASHELP.CLASS into either a 1 or a 2 -- as a numeric variable. The PUT function creates a character value of either '1' or '2' and then the INPUT function takes that character string and converts it to a number.

cynthia
[pre]
proc format;
value $CONV 'F' = '1'
'M' = '2';
run;

data class;
set sashelp.class;
newnum = input(put(sex,$conv.),best.);
run;

proc print data=class noobs;
title 'show NEWNUM variable and use SUM statement to prove it is a number';
var name sex newnum;
sum newnum;
run;
[/pre]
Contributor
Posts: 32

Re: character string to numeric value conversion

Posted in reply to Cynthia_sas
That's a winner.

THANKS Cynthia!!!
Respected Advisor
Posts: 3,799

Re: character string to numeric value conversion

An INFORMAT may be a good choice. As it offers some advantages over a FORMAT with the UPCASE and JUST options and it creats the numeric value directly.

[pre]
proc format;
INvalue news(just upcase) 'EAST'=1 'WEST'=2 'NORTH'=3 'SOUTH'=4;
run;

data news;
length news $8;
do news='East', 'WEST', ' NORTH', 'SOUTH';
code = input(news,news8.);
output;
end;
run;
proc print;
run;

Obs news code

1 East 1
2 WEST 2
3 NORTH 3
4 SOUTH 4


[/pre]

As in this case where the default W for the user defined INFORAMT is 5, be sure to specify a W that is wide enough to read the entire field. JUST takes place after the read but before the comparison with INVALUESlist.
Contributor
Posts: 32

Re: character string to numeric value conversion

Posted in reply to data_null__
THANKS data_null_;!!!

I like this because it creates the numeric value directly.

This is a great forum.
Ask a Question
Discussion stats
  • 4 replies
  • 242 views
  • 0 likes
  • 3 in conversation