Hi all, I have some variables named like this var_1, var_2, var_3.....var_50. Right now it is up to var_50, but anytime if a new case is added to the data, it can be var_51, var_52 etc. So, I use the term var_: when I run frequency or crosstabs to avoid repeated codes and to avoid writing new codes whenever a new case is added. But whenever I use 'var_:' in 'if then statement', it does not work. Any suggestion? One thing to mention that var_1 is a neumaric variable but I but similar character variable too (eg. hlt_1, hlt_2, hlt_3 etc.) with which I have the same problem.
here is an example of code that I am using:
If var_: in (5) then flag=1;
if hlt_: in ('100897') then flag=1;
Thank you!
You cannot use multiple variables on the left side of the IN operator, so you will have to change the expression, e.g. using WHICHN or WHICHC, e.g.
If whichn(5,of var_:) then flag=1;
if whichc('100897',of hlt_:) then flag=1;
You cannot use multiple variables on the left side of the IN operator, so you will have to change the expression, e.g. using WHICHN or WHICHC, e.g.
If whichn(5,of var_:) then flag=1;
if whichc('100897',of hlt_:) then flag=1;
Hi, It worked. Thank you very much.
@nirsan wrote:
Hi, It worked. Can you please suggest what will be the code if I want to check the following condition?
If var_: not in (5) then flag=1;
if hlt_: not in ('100897') then flag=1;
Thank you!
That is so trivial that you can easily find the answer on your own. Just start the tool between your ears.
Hint: negate the whole condition.
Hi @nirsan,
Alternatively, you can use the IN operator with an array:
data want;
set have;
array var_[50];
array hlt_[50];
if 5 in var_ then flag1=1;
if '100897' in hlt_ then flag2=1;
run;
To avoid the hardcoded array dimensions (50) you may want to replace the two ARRAY statements by
array var_[*] var_:;
array hlt_[*] hlt_:;
Note, however, that with this array definition (in general) the numeric suffix of a variable matches the corresponding array index only if the variables are ordered by the suffix in the dataset. Otherwise, for example, var_[3] could be var_2.
Edit:
@nirsan wrote:
(...) Right now it is up to var_50, but anytime if a new case is added to the data, it can be var_51, var_52 etc. (...)
That's why in many cases a "long" (vertical) data structure is preferable where a single variable, say, var holds the values of var_1, var_2, ... in different observations. Adding "a new case" then just means adding new observations (which is a routine operation), while the data structure remains unchanged.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.