Search code examples
macrosspss

Looping through a set of variables sharing the same prefix


I routinely work with student exam files, where each response to an exam item is recorded in points. I want to transform that variable into 1 or 0 (effectively reducing each item to Correct or Incorrect).

Every dataset has the same nomenclature, where the variable is prefixed with points_ and then followed by an identification number (e.g., points_18616). I'm using the following syntax:

RECODE points_18616 (0=Copy) (SYSMIS=SYSMIS) (ELSE=1) INTO Binary_18616.
VARIABLE LABELS  Binary_18616 'Binary Conversion of Item_18616'.
EXECUTE.

So I end up creating this syntax for each variable, and since every dataset is different, it gets tedious. Is there a way to loop through a dataset and perform this transformation on all variables that are prefixed with points_?


Solution

  • Here is a way to do it:

    First I'll create a little fake data to demonstrate on:

    data list list/points_18616 points_18617 points_18618 points_18619 (4f2).
    begin data
    4 5 6 7
    5 6 7 8
    6 7 8 9
    7 8 9 9
    end data.
    
    * the following code will create a list of all the relevant variables in a new file.
    SPSSINC SELECT VARIABLES MACRONAME="!list" /PROPERTIES  PATTERN = "points_*".
    
    * now we'll use the created list in a macro to loop your syntax over all the vars.    
    define !doList ()
    !do !lst !in(!eval(!list))
    RECODE !lst (0=Copy) (SYSMIS=SYSMIS) (ELSE=1) INTO !concat("Binary", !substr(!lst,7)).
    VARIABLE LABELS  !concat("Binary", !substr(!lst,7))  !concat("'Binary Conversion of Item",!substr(!lst,7) ,"'.").
    !doend
    !enddefine.
    
    !doList.
    EXECUTE.