Help using Base SAS procedures

Subset '30'-'33' (character variable)

Frequent Contributor
Posts: 76

Subset '30'-'33' (character variable)



Iam using SAS 7.1


I am quite new to SAS, so pardon if my question sounds basic.


i have a range of character variable.





'24',  '30' , '31', '32', '33', '34'


I only want to select the data for Food_Type = '30' - '33'



SAS Code 1:


data test;

set test;

where Food_Type in ('30' -'33');



SAS Code 2:


data test;

set test;

where Food_Type in ('30') or Food_Type in ('31') or Food_Type in ('32') or Food_Type in ('33') ;



SAS Code 1 doesn't work but SAS code 2 does. However, it is very tedious to type out all the Food_Type values I want. Is there a faster way I could select '30' - '33'?


Thank you

Regular Contributor
Posts: 161

Re: Subset '30'-'33' (character variable)

[ Edited ]

Try this:


where '30' LE Food_Type LE '33';



Hope it helps.... Good Luck...!!!

Kannan Deivasigamani
Super Contributor
Posts: 275

Re: Subset '30'-'33' (character variable)

data want;

     set have;

     where food_type between '30' and '33';   *or where  '30'<=food_type<='33';





Respected Advisor
Posts: 4,738

Re: Subset '30'-'33' (character variable)

[ Edited ]
where food_type in ('24',  '30' , '31', '32', '33', '34')


Even if only dealing with digits don't use ranges with character variables as you might get unexpected results like below:


data _null_;
  if '99'>'100' then put '99>100';
  else put '99<=100';

Result in log:

Super User
Posts: 6,785

Re: Subset '30'-'33' (character variable)

While you have many solutions that will work with the example you gave, heed Patrick's warning.  There are many cases where you would run into trouble.  For example, if your FOOD_TYPE variable is actually 3 characters long, the solutions proposed would also include '301'.  That falls within the range of "30" to "33".


Once your first digit can change, the problems get worse.  For example, if you tried this:


where ('39' <= food_type <= '41');


That range also includes a few values you might not want, such as "4" and either "3F' or "4F" (depends on the operating system).


You will get by in this particular case, but you will need to understand how SAS compares character strings to be safe in the future.



SAS Employee
Posts: 340

Re: Subset '30'-'33' (character variable)

This works even when your first digit changes:

where   30 <=input(Food_Type, 3.) <= 100


Valued Guide
Posts: 864

Re: Subset '30'-'33' (character variable)

This selects the range, including 30 and 33:


data want;
set have;
where food_type between 30 and 33;

Ask a Question
Discussion stats
  • 6 replies
  • 7 in conversation