Quartz | Level 8

## new variable with if then statements

dataset:

subj  q1   q2   q3   q4   q5    q_total  newvar

1       1    3.1  2.1   1    1        8.2

2       1    2.1  4.1   1    3      11.2

3       1    1.2  1      0    1.1     4.3

4       0      1    0      1    0       2

i would like to creat a new variable (newvar), where if q1 <=1 and if q2 is <= 1 and if q3 is <=1 and if qtotal is <= 8, then newvar =1 , otherwise newvar =0.

so newvar would look like:

newvar

0

0

0

1

1 ACCEPTED SOLUTION

Accepted Solutions
Opal | Level 21

## Re: new variable with if then statements

newvar = q1 <=1 and q2 <= 1 and q3 <=1 and qtotal <= 8;

PG
6 REPLIES 6
Opal | Level 21

## Re: new variable with if then statements

newvar = q1 <=1 and q2 <= 1 and q3 <=1 and qtotal <= 8;

PG
Quartz | Level 8

## Re: new variable with if then statements

hmm im not getting newvar to equal 1 with that code

Super User

## Re: new variable with if then statements

@PGStats is being very terse.

His solution works for what you are doing because SAS treats true results as 1 and false as 0. So Newvar is the result of all of those comparisons, true or false.

You may want to consider if "otherwise newvar=0" includes cases of missing values. Missing are less than any value. So in this specific interest if all of the q variables are missing then newvar would be 1.

Quartz | Level 8

## Re: new variable with if then statements

is adding q1 ne . and q2 ne . and q3 ne . to PG's statement the best option?

Opal | Level 21

## Re: new variable with if then statements

Your logical expression yields true (=1) when q1, q2, q3, or q_total are missing because missing is considered by SAS as inferior to any non-missing value. You can change the expression so that missing values will yield false, as demonstrated:

``````data test;
input subj  q1   q2   q3   q4   q5    q_total;
newvarTrue = q1 <=1 and q2 <= 1 and q3 <=1 and q_total <= 8;
newvarFalse = -q1 >= -11 and -q2 >= -1 and -q3 >= -1 and -q_total >= -8;
datalines;
1       1    3.1  2.1   1    1        8.2
2       1    2.1  4.1   1    3      11.2
3       1    1.2  1      0    1.1     4.3
4       0      1    0      1    0       2
5       .      1    0      1    0       2
;

proc print; run;
``````