BookmarkSubscribeRSS Feed
NilsNoh
Calcite | Level 5

Hey Guys,

 

this question was probably already asked before but I am not only new to SAS, but also new to this forum, so please bear with me.

 

I have a dataset where I wanted to sort a character variable with length 18, although it is a character variable it only contains numbers (IDs). If I try to sort this variable, I get an error because in at least one observation there are letters mixed into the ID.

 

How do I find out how many observations contain letters, I think I have to use the anyalpha command, but not quite sure how to apply it.

 

Thanks in advance!

5 REPLIES 5
RW9
Diamond | Level 26 RW9
Diamond | Level 26

Can you use sortseq=linguistic (numeric_collation=on) in your proc sort?

Anyhows:

number_of_chars=lengthn(compress(id," ","ka"));

Pop that in a datastep and it will tell you how many alphas are in the id string.  ka = keep alpha.

Amir
PROC Star

Hi,

 

To find the number of observations, you could try proc sql as in the following example:

 

/* set up an id variable with some containing alphabetic characters */
data have;
   set sashelp.class;

   length id $ 8;

   /* add alphabetics to id if name begins with 'J' */
   if name eq: 'J' then
      id = cats('ABC',id);
   else
      id = cats(_n_);
run;

%let id_alpha = 0;

/* save the count of id's with alphabetic characters into a macro variable */
proc sql noprint;
   select
      count (*)
   into
      :id_alpha
   from
      have(keep = id)
   where
      anyalpha(id)
   ;
quit;

%put id_alpha = &id_alpha;

 

 

Regards,

Amir.

NilsNoh
Calcite | Level 5

Cheers Guys!

 

Tried the methods and both work well and deliver the same result, thank you!

Amir
PROC Star

Thanks @NilsNoh.

 

You can mark either solution as accepted.

 

Regards,

Amir.

MadhuKorni
Quartz | Level 8

Anyalpha is used to find the first occurrence of an alphabet in a string. 

 

data want;
set have;
retain cnt 0;;
Num_of_Chars = lengthn(compress(ID,,'d')); *If you want to include special characters(if exist);
Num_of_Chars = lengthn(compress(ID,,'ka')); *If you have only alphabets and digits;
if Num_of_Chars gt 0 then cnt=cnt+1;
call symput("No_Of_Obs",cnt);
run;
How to Concatenate Values

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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

Discussion stats
  • 5 replies
  • 5161 views
  • 0 likes
  • 4 in conversation