Tikhon
Tikhon

Reputation: 451

SPSS compute variable from other variables

I am trying to create an "index" variable (*mathematically not an index) that I called 'Res' from the other variables in my data set. Here is the code I am trying to use:

COMPUTE Res = 0.
EXECUTE.

DO IF(Q33 = 6).
    COMPUTE RES = Res - 1.

IF(Q34 = 7).
    COMPUTE Res = Res - 1.

IF(Q35 = 1 OR Q35 = 2).
    COMPUTE Res = Res + 1.

END IF.
EXECUTE. 

This is not working though - my variable does not change. Tried with ELSE IF and that does change the variable but of course that only implements one change because of the "else" - only one change gets implemented.

To clarify I am trying to compute a score for Res, so I want the algebraic operations performed step by step. So, for instance, for a respondent who has

Q33 = 6, Q34 = 7 and Q 35 = 2

all 3 if conditions are true so Res should be 0 -1 -1 +1 = -1

For a respondent who has

Q33 = 2, Q34 = 2 and Q 35 = 1

The first two if conditions are false and the last one is true so Res should be 0 + 1 = 1

For a respondent who has

Q33 = 2, Q34 = 2 and Q 35 = 3

All if conditions are false, so Res should be 0.

Thanks.

Upvotes: 1

Views: 383

Answers (2)

eli-k
eli-k

Reputation: 11350

From your description, you need each of the conditional transformations to be carried out independently of the others (this is also apparent in the solution you offered).
So the problem with your original code has to do with using do if instead of just if. All the commands included in a do if will only be performed if the do if condition is met. In your case the following if commands were included in the do if loop and so weren't carried out if (Q33 ne 6).

do if is used for conditional commands, but for a single transformation it isn't needed - if is enough. So all you would need is:

COMPUTE Res=0 
IF(Q33 = 6) Res = Res - 1.
IF(Q34 = 7) Res = Res - 1.
IF(Q35 = 1 OR Q35 = 2) Res = Res + 1.
IF(Q35 = 5 OR Q35 = 6) Res = Res - 1.

Finally, SPSS gives a numeric value of 0 to a false logical statement and 1 to a true one. Therefore, this should do the same job (including the initial definition of RES):

compute RES = 0 - (Q33 = 6) - (Q34 = 7) + (Q35 = 1 OR Q35 = 2) - (Q35 = 5 OR Q35 = 6).

Please note, this last method is problematic if you have missing values in the conditional variables. In such a case you should use this instead:

compute RES = sum(0, - (Q33 = 6), - (Q34 = 7), (Q35 = 1 OR Q35 = 2), - (Q35 = 5 OR Q35 = 6)).

Upvotes: 1

Tikhon
Tikhon

Reputation: 451

This is probably not the best way of doing it but the following works:

DO IF(Q33 = 6).
    COMPUTE RES = Res - 1.
END IF.

DO IF(Q34 = 7).
    COMPUTE Res = Res - 1.
END IF.

DO IF(Q35 = 1 OR Q35 = 2).
    COMPUTE Res = Res + 1.
END IF.

DO IF(Q35 = 5 OR Q35 = 6).
    COMPUTE Res = Res - 1.
END IF.
EXECUTE.

Upvotes: 0

Related Questions