BookmarkSubscribeRSS Feed
☑ This topic is solved. Need further help from the community? Please sign in and ask a new question.
epialy
Calcite | Level 5

Hi all,

 

I have four variables that are coded as 0/1, and want to write if-then statements to produce a new variable if two or more of the variables =1. I could write out every feasible combination of the variables, but I'm certain there must be a more efficient and elegant way than:

if (var1=1 and var2=1 and var3=0 and var4=0) or (var1=1 and var2=0 and var3=1 and var4=0) or...... and so on

then newvar=1

 

But I'm a fairly new with SAS and not sure how to approach differently. Any insight would be appreciated. Thanks!

1 ACCEPTED SOLUTION

Accepted Solutions
AMSAS
SAS Super FREQ

How about a simple sum

data want ;
	/* set up test data */
	do var1=0 to 1 ;
		do var2=0 to 1 ;
			do var3=0 to 1 ;
				do var4=0 to 1 ;
					/* code to set newvar if 2 or more var1-4 are set to 1 */
					x=sum(var1,var2,var3,var4) ;
					if x>1 then
						newvar=1 ;
					else 
						newvar=0 ;
					/* output all variables to dataset */ 
					output ;
					/* end  do loops for test data */
				end ;
			end ;
		end ;
	end ;
run ;

View solution in original post

2 REPLIES 2
AMSAS
SAS Super FREQ

How about a simple sum

data want ;
	/* set up test data */
	do var1=0 to 1 ;
		do var2=0 to 1 ;
			do var3=0 to 1 ;
				do var4=0 to 1 ;
					/* code to set newvar if 2 or more var1-4 are set to 1 */
					x=sum(var1,var2,var3,var4) ;
					if x>1 then
						newvar=1 ;
					else 
						newvar=0 ;
					/* output all variables to dataset */ 
					output ;
					/* end  do loops for test data */
				end ;
			end ;
		end ;
	end ;
run ;
Reeza
Super User
NewVar = sum(of var1-var4) > 1;

Condensing @AMSAS solution somewhat you can use the above as an example. Exactly how you list the variables in the SUM() can vary a few ways, from explicitly listing them to shortcut lists.

 

Here is a reference that illustrates how to refer to variables and datasets in a short cut list:
https://blogs.sas.com/content/iml/2018/05/29/6-easy-ways-to-specify-a-list-of-variables-in-sas.html

SAS Innovate 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
Register now!

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
  • 2 replies
  • 369 views
  • 4 likes
  • 3 in conversation