I have a character variable that takes on the following values.
A 111 C111
AB 1234 D311
A/B AA A1212
BC 123 D123
CSA JJK P00
I would like to grab the number between the first and second space, if that part is indeed a number. I would like to get:
111
1234
.
123
.
How can I achieve this? Thanks.
You can use the scan function to find the second word, when a blank space is the delimiter between words. Use the input function to convert that second word to a number.
data have;
length char_string $ 25;
input char_string $25. ;
datalines;
A 111 C111
AB 1234 D311
A/B AA A1212
BC 123 D123
CSA JJK P00
;
run;
proc print data=have;
run;
data want;
set have;
middle_number=input(scan(char_string,2,' '),12.);
run;
proc print data=want;
run;
You can use the scan function to find the second word, when a blank space is the delimiter between words. Use the input function to convert that second word to a number.
data have;
length char_string $ 25;
input char_string $25. ;
datalines;
A 111 C111
AB 1234 D311
A/B AA A1212
BC 123 D123
CSA JJK P00
;
run;
proc print data=have;
run;
data want;
set have;
middle_number=input(scan(char_string,2,' '),12.);
run;
proc print data=want;
run;
That code will show notes in the log, when the second word has letters. To prevent those notes in the log, you can test to see if there are any letters in the second word before converting it to a number.
if anyalpha(scan(char_string,2,' '))=0 then
middle_number=input(scan(char_string,2,' '),12.);
Another way to suppress these warnings: Use the ?? argument with the input function.
data want;
set have;
middle_number=input(scan(char_string,2,' '),?? best32.);
run;
Don't miss out on SAS Innovate - Register now for the FREE Livestream!
Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.
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.