BookmarkSubscribeRSS Feed
veblen
Calcite | Level 5
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
4 REPLIES 4
Cynthia_sas
SAS Super FREQ
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]
veblen
Calcite | Level 5
That's a winner.

THANKS Cynthia!!!
data_null__
Jade | Level 19
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.
veblen
Calcite | Level 5
THANKS data_null_;!!!

I like this because it creates the numeric value directly.

This is a great forum.

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

What is Bayesian Analysis?

Learn the difference between classical and Bayesian statistical approaches and see a few PROC examples to perform Bayesian analysis in this video.

Find more tutorials on the SAS Users YouTube channel.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 4 replies
  • 1568 views
  • 0 likes
  • 3 in conversation