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-2024.png

Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.

Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.

 

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.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

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