DATA Step, Macro, Functions and more

if statement

Reply
Regular Contributor
Posts: 241

if statement

Hello,

 

I want simplify a complex if statement:

 

data one;

set had;

 if a in(1, 2, 3) or  b in (1,2,3)  or c in (1,2,3) then x=123;

run;

 

My question is can I simplify the if statement like this?:

 

data need;

set had;

 if (a or b or c) in (1,2,3) then x=123;

run;

 

Thanks

 

Super User
Posts: 10,044

Re: if statement

Posted in reply to GeorgeSAS

No.That is not right.

However, if you are using SAS/IML , there is a function ELEMENT() can do that.

PROC Star
Posts: 1,760

Re: if statement

Posted in reply to GeorgeSAS

No you can't do this.

 

If you have a long list of value, you can store them once only:

%let list_values=1 2 3;

 if a in(&list_values) or  b in (&list_values) or c in (&list_values) then x=123;

 

If you have a long list of variables you can use a macro loop to generate the statements.

 

%macro loop;

%local i list_values list_variables;

%let list_values=1 2 3;

%let list_variables= a b c;

if 0

%do i=1 %to 3;

or %scan(&list_variables, &i) in (&list_values)

%end;

 then x=123;

%mend;

%loop;

Super User
Posts: 19,869

Re: if statement

Posted in reply to GeorgeSAS

Can A/B/C variables have any value at all, if not there may be other options. 

 

An array is probably easier and faster than a macro, especially if the values aren't 1/2/3.

 

data want;
set have;
array var_list(*) a b c;
flag=0;
do i=1,2,3;
	if whichn(i, of var_list(*))>0 then do;
		flag=123;
		leave;
	end;
end;
run;

 

 

 

Super User
Super User
Posts: 7,992

Re: if statement

Posted in reply to GeorgeSAS

This example concatenates the three values, then strips out all occurences of 1,2,3, and thus any length > 0 indicates a character not in the list 1,2,3.

data want;
  a=1; b=3; c=3; 
  if lengthn(compress(cats(a,b,c),"123"))=0 then x=123;
run;
Super User
Posts: 19,869

Re: if statement

[ Edited ]

That assumes single digit values?

Super User
Super User
Posts: 7,992

Re: if statement

Yes, thats all he posted in the OP.  It could be that b=12 would pass that logic check, but be inaccurate as > 3, but he hasn't mentioned that.  If it is the case, then use catx() with a delimiter, and remove delimter+digit.

Regular Contributor
Posts: 241

Re: if statement

any value. (1,2,3) just an example, maybe there are more characters such as ('abc','qwe',.....more)
Super User
Super User
Posts: 7,992

Re: if statement

Posted in reply to GeorgeSAS

In which case then no.  If there is no logical reason to arrive at a formula then one wont exist.  As mentioned above arrays are probably your best bet, i.e.:

 

data want;
  set have;
  array tmp <list of variables>;
  do over tmp;
    if tmp in (<set of values>) then result_value=<result>;
  end;
run;
Ask a Question
Discussion stats
  • 8 replies
  • 349 views
  • 2 likes
  • 5 in conversation