Hello Community,
I need some help converting a character variable to a numeric variable. I have provided below an example of the different types of values of the character variable as well as the desired numeric forms of the values for the new variable. The character variable is in the $254. format. Please also note that some of the values of the character variable have nondigits in the form of a dash (e.g., 2-4). For these cases, I would like to write out the last digit of the character value (i.e., the digit to the right of the dash) for the new numeric variable as shown below (e.g., 2-4 --> 4). Any suggestions on how to do this would be much appreciated!!
Old_var_character | New_var_numeric |
.5 | 0.5 |
1 | 1 |
5.5 | 5.5 |
10 | 10 |
10.5 | 10.5 |
100 | 100 |
300 | 300 |
1-2 | 2 |
2-4 | 4 |
2-8 | 8 |
4-8 | 8 |
Below should do it:
data have;
input Old_var_character $;
if find(Old_var_character,"-") then
New_var_numeric = input(substr(Old_var_character,3,3),best12.);
else New_var_numeric = input(Old_var_character,best12.);
datalines;
.5
1
5.5
10
10.5
100
300
1-2
2-4
2-8
4-8
;
run;
Here's one way that works those sorts of examples:
data junk; input var $; numvar = input(var,?? 12.); if missing(numvar) then numvar = input(scan(var,2,'-'),?? 12.); datalines; 4-8 ;
The input just to have something to work with.
The first "numvar =" attempts to convert the value as is. The ?? tells SAS to suppress the invalid data messages you get with the dash values. If the result of the first conversion is missing (the result when converting invalid data) then use the Scan function to get the second value and input that to numeric.
If you have any negative values then you need to provide examples and how you expect them to be used as the - also indicates negative and if you have "-4-8" then the first dash would be a delimiter for the SCAN function and find 4 as the numeric value.
Below should do it:
data have;
input Old_var_character $;
if find(Old_var_character,"-") then
New_var_numeric = input(substr(Old_var_character,3,3),best12.);
else New_var_numeric = input(Old_var_character,best12.);
datalines;
.5
1
5.5
10
10.5
100
300
1-2
2-4
2-8
4-8
;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.