loopsvariablesconditional-statementsspssmulti-level

(SPSS) Assign values to remaining time point based on value on another variable, and looping for each case


I am currently working on analyzing a within-subject dataset with 8 time-ordered assessment points for each subject.

The variables of interest in this example is ID, time point, and accident.

I want to create two variables: accident_intercept and accident_slope, based on the value on accident at a particular time point.

For the accident_intercept variable, once a participant indicated the occurrence of an accident (e.g., accident = 1) at a specific time point, I want the values for that time point and the remaining time points to be 1.

For the accident_slope variable, once a participant indicated the occurrence of an accident (e.g., accident = 1) at a specific time point, I want the value of that time point to be 0, but count up by 1 for the remaining time points until the end time point, for each subject.

The main challenge here is that the process stated above need to be repeated/looped for each participant that occupies 8 rows of data.

Please see how the newly created variables would look like: enter image description here

I have looked into the instruction for different SPSS syntax, such as loop, the lag/lead functions. I also tried to break my task into different components and google each one. However, I have not made any progress :)

I would be really grateful of any helps and directions that you provide.


Solution

  • Here is one way to do what you need using aggregate to calculate "accident time":

    if accident=1 accidentTime=TimePoint.
    aggregate out=* mode=addvariables overwrite=yes /break=ID/accidentTime=max(accidentTime).
    if TimePoint>=accidentTime Accident_Intercept=1.
    if TimePoint>=accidentTime Accident_Slope=TimePoint-accidentTime.
    recode Accident_Slope accidentTime (miss=0).
    

    Here is another approach using the lag function:

    compute Accident_Intercept=0.
    if accident=1 Accident_Intercept=1.
    if $casenum>1 and id=lag(id) and lag(Accident_Intercept)=1 Accident_Intercept=1.
    compute Accident_Slope=0.
    if $casenum>1 and id=lag(id) and lag(Accident_Intercept)=1 Accident_Slope=lag(Accident_Slope) +1.
    exe.