Search code examples
spss

SPSS variable scope in nested if


How would you do the following in spss:

var participant_number = 0.

DO IF (condition =1 AND trial_order = 1).
    participant_number = ppnr.
    DO IF (ppnr = participant_number).
        COMPUTE start_condition = 1.
    END IF.
ELSE.
    participant_number = ppnr.
    DO IF (ppnr = participant_number).
        COMPUTE start_condition = 0.
    END IF.
END IF.

The variable participant_number needs to be defined for the inner loops and not change throughout the inner if. I am just trying to set a value for all the participant cases if the participant fulfills a condition.


Solution

  • In SPSS, in general, (with exceptions, but let's keep things simple for now), variables are global. If they come from the dataset, they can be used in syntaxes without fear of going out of scope. Note that variables need to be "computed"/created first, before being used. You can do that with syntax or manually in the Data window.

    DO IF is useful if you want to perform multiple transformations. Otherwise, a structure like

    IF [condition][transformation]. EXECUTE.

    would do the trick.

    If I understood your goal correctly, you can re-write your code like this:

    ***create a temporary variable, to check each case if your condition is met. Set the temporary variable to 0 as default value.
    compute tempvar=0.
    ***then set it to 1, if condition is met.
    ***This is at case level, not participant level.
    if condition=1 and trial_order=1 tempvar=1.
    exe.
    ***aggregate the temp variable, from case level at participant level.
    ***for each participant (ppnr), it will look at all values of tempvar, and set the start_condition as the maximum of tempvar - either 0 or 1.
    AGGREGATE
      /OUTFILE=* MODE=ADDVARIABLES
      /BREAK=ppnr
      /start_condition=MAX(tempvar).
    
    ***optional.
    delete variable tempvar.
    

    At the end, start_condition will be 1 for each case of a participant if (condition =1 AND trial_order = 1) is met for at least one case of that participant; otherwise, it will be 0.