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;
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.
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.