Hi all,
I'm sure this is answered somewhere else but I can't seem to find it, so I'll ask here. I'm new to SAS and am having trouble converting a char data variable to a numeric one. The variable in question is a list of data all formatted as a mix of character: 002AB0001, 002AB0002, 002AB0003 and so on). I am hoping to change it to only the last 4 digits (ex: 0001, 0002, 0003). Any suggestions on the proper code for this?
I've tried a few commands, including the one below, but am not sure how to specify to SAS that I'm interested in the last 4.
Thank you all
failed attempt:
data new_set;
old_var = "002AB0001";
numeric_var = input(old_var,4.);
run;
data new_set;
old_var = "002AB0001";
numeric_var = input(scan(old_var,-1,,'kd'),best.);
run;
@sms39 wrote:
Hi all,
I'm sure this is answered somewhere else but I can't seem to find it, so I'll ask here. I'm new to SAS and am having trouble converting a char data variable to a numeric one. The variable in question is a list of data all formatted as a mix of character: 002AB0001, 002AB0002, 002AB0003 and so on). I am hoping to change it to only the last 4 digits (ex: 0001, 0002, 0003). Any suggestions on the proper code for this?
I've tried a few commands, including the one below, but am not sure how to specify to SAS that I'm interested in the last 4.
Thank you all
failed attempt:
data new_set;
old_var = "002AB0001";
numeric_var = input(old_var,4.);
run;
You are asking SAS to read the FIRST 4 characters as try to convert to a number. But the letter A is not valid.
To get the LAST 4 characters use SUBSTR() function first. If you know you always want from the 5th character onwards use can just use on argument to SUBSTR(). The width you use for the INFORMAT doesn't really matter if you want to read the whole string. The maximum width that normal numeric informat will read is 32 bytes.
numeric_var = input(substr(old_var,5),32.);
If the prefix length varies then count backwards from the end. Subtracting 3 from the length will get the last 4 characters.
numeric_var = input(substr(old_var,length(old_var)-3),32.);
If the numeric suffix length varies then start where it begins instead.
numeric_var = input(substr(old_var,findc(old_var,,'dk',-length(old_var))),32.);
data new_set;
old_var = "002AB0001";
numeric_var = input(scan(old_var,-1,,'kd'),best.);
run;
This worked like a charm, thank you!
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.