If a var is defined as char,
length x $6.;
How do I check the values of this var that has numbers only?
Example, if x has
12346
1a2b3c
1+abc
How do I find numeric values such as 12346?
Or is there a way to look for values that's alphabets? special chars?
Thanks!
Here's one way:
data have;
input x $6.;
length x $6.;
datalines;
12346
1a2b3c
1+abc
abcde
;
run;
data string_with_only_numbers;
set have;
if anydigit(x) and not anyalpha(x);
run;
data string_with_only_alpha;
set have;
if not anydigit(x) and anyalpha(x);
run;
Courtesy of this post: https://communities.sas.com/t5/SAS-Procedures/Check-numeric-values-in-alphanumeric-variables/td-p/19...
An easy way to test if the value is a valid representation of a number is to try to convert it to a number.
Just use the normal numeric informat. Use the ?? modifier to suppress error messages.
data want;
set have;
number=input(x,??32.);
valid_number = not missing(number);
run;
Or if you want to accept strings with commas and dollar signs ( like 1,200 and $5,000) then use the COMMA informat instead.
If X can hold strings that are longer than 32 bytes then you might want to also test that the value is not too long.
data want;
set have;
if length(strip(x))<=32 then number=input(strip(x),??32.);
valid_number = not missing(number);
run;
Here's one way:
data have;
input x $6.;
length x $6.;
datalines;
12346
1a2b3c
1+abc
abcde
;
run;
data string_with_only_numbers;
set have;
if anydigit(x) and not anyalpha(x);
run;
data string_with_only_alpha;
set have;
if not anydigit(x) and anyalpha(x);
run;
Courtesy of this post: https://communities.sas.com/t5/SAS-Procedures/Check-numeric-values-in-alphanumeric-variables/td-p/19...
data have; input x $6.; length x $ 6; flag=ifn(notdigit(strip(x)),0,1); datalines; 12346 1a2b3c 1+abc abcde ; run;
Join us for SAS Innovate 2025, our biggest and most exciting global event of the year, in Orlando, FL, from May 6-9. Sign up by March 14 for just $795.
SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.