Fluorite | Level 6

## Combining Two Variables

I want to combine two variables to create one new variable where group 1 indicates those who use both cigarettes and alcohol (coded 1) and group 2 indicates those who just use either cigarettes or alcohol or use neither (coded 2).

The variable ciguse is coded 1 for cigarette use and 2 for no cigarette use. The variable alcoholuse is coded 1 for alcohol use and 2 for no alcohol use.

Does the below code adequately capture everyone in each group and create the intended variable?

if ciguse=1 and alcoholuse=1 then bothsubstances=1;
*else if ciguse=2 or alcoholuse=2 then bothsubstances=2;
*else bothsubstances=.;
4 REPLIES 4
Super User

## Re: Combining Two Variables

Remove the comment asterisks and try it. Methinks it will work, but testing beats guessing.

Fluorite | Level 6

## Re: Combining Two Variables

Sorry, yes, the asterisks shouldn't be there!

if cursmk=1 and cursmkls=1 then tobacco2=1;
else if cursmk=2 or cursmkls=2 then tobacco2=2;
else tobacco2=.;
Rhodochrosite | Level 12

## Re: Combining Two Variables

Hello,

Assuming alcoholuse end ciguse can take values 1, 2 and ., here are the possible outcomes.

You can check if it fits your needs.

/* Possible values for ...use variables : 1, 2, . */
data usevals;
input x;
cards;
1
2
.
;
run;

/* We generate all possible combinations of alcoholuse and ciguse */
proc sql noprint;
CREATE TABLE have AS
SELECT a.x AS ciguse, b.x AS alcoholuse
FROM usevals a, usevals b;
quit;

data want;
set have;
if ciguse=1 and alcoholuse=1 then bothsubstances=1;
else if ciguse=2 or alcoholuse=2 then bothsubstances=2;
else bothsubstances=.;
run;
Ammonite | Level 13

## Re: Combining Two Variables

One problem is that your in/output values aren't encoded as Booleans, which would be 1 = use and 0 = no use. That would stand to reason seeing that in SAS 1=true and 0=false. This way, the logical expression (sig and alc) would yield true in the case of both sig use and alc use and false otherwise. This is why in order to get what you require you need the IF-THEN-ELSE bunch or, more concisely, the IFN function, such as the expression:

cig_and_alc = ifN (cig=1 and alc=1, 1, 2) ;

Booleans can still be used; however, due to the odd way the values are encoded, some funny arithmetic has to be added:

data _null_ ;
input cig alc ;
cig_alc = 2 - ((2 - cig) and (2 - alc)) ;
put cig alc cig_alc= ;
cards ;
1 1
1 2
2 1
2 2
;
run ;

Which yields:

1 1 cig_alc=1
1 2 cig_alc=2
2 1 cig_alc=2
2 2 cig_alc=2

If the values were encoded as normal Booleans, the expression for cig_alc would be much simpler:

data _null_ ;
input cig alc ;
cig_alc = cig and alc ;
put cig alc cig_alc= ;
cards ;
1 1
1 0
0 1
0 0
;
run ;

and the result would be much more, uh, logical:

1 1 cig_alc=1
1 0 cig_alc=0
0 1 cig_alc=0
0 0 cig_alc=0

Kind regards

Paul D.

Discussion stats
• 4 replies
• 573 views
• 2 likes
• 4 in conversation