I have a character variable representing various US states that I need to convert to numberical.
data have;
State |
data want;
State_num
1
2
3
so one so forth
I know I can achieve this using :
If state=”Kentucky” then state_num=1;
If state=”Louisiana” then state_num=2;
and so one so forth.
But this would be lenghty, does anyone know what would be the optimal way of converting from character to numeric.
Thanks.
You can create a format that gives a unique number when the Statename is given.
Other easy way is to use _N_, the obsevation number, to be attached to each state.
The former is better.
There is no need to list all Names to make the format. We can create format using the data set.
I show how it can be made.
Your interest is not known as how you will be using the crime rates. If it is known, an approprite solution can be given.
Besides the Format, Hash Objects and Array with PIBw. can be used.
data have;
input state &$15.;
datalines;
Kentucky
Louisiana
Maine
Maryland
Massachusetts
Michigan
Minnesota
Mississippi
Missouri
Montana
Nebraska
Nevada
New Hampshire
New Jersey
New Mexico
New York
North Carolina
North Dakota
Ohio
Oklahoma
Oregon
Pennsylvania
Rhode Island
South Carolina
;
run;
data cnt;
retain fmtname 's2num' type 'I';
set have end = last;
start = state;
label = _N_;
output;
if last then do;
hlo = 'O';
label = 0;
output;
end;
run;
proc sort data = cnt nodupkey;
by start;
run;
proc format cntlin = cnt;
run;
We can verify the Format by cycling the original data set. Note the use of INPUT(STATE, s2num.) to get the unique number for a given State.
data want;
set have;
state_id = input(state, s2num.);
run;
There are also the FIPS code that you can use. Look into the functions. I know you can go from state abbreviation to code.
I think we're missing some information, please clarify your requirements.
I was suggesting mapping the State Names to FIP codes, I think there's a SAS function that maps this.
If order matters then please clarify your requirements.
If your data is one record per state then you can define your own code.
data want ;
set have ;
state_num + 1;
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.