Search code examples
spss

Renaming variable with a suffix within an SPSS Macro


I use the following code to winsorize variables in my dataset using SPSS. In the line where it says COMPUTE !var = MAX(MIN(!var, maxval), minval)., I want it to create a new variable with _w as the suffix. Of course, COMPUTE !var_w = MAX(MIN(!var, maxval), minval). will not work. Any solutions, preferably without using Python? Also, is there a way to loop this so that I can include more than one variable when I execute it? For example, !winsor vars = roa, leverage, roe lowpc = 1 hipc = 1..

DEFINE !winsor (var = !TOKENS(1) / lowpc = !TOKENS(1) / hipc = !TOKENS(1))
COMPUTE nobreak=1.
RANK VARIABLES = !var (A) BY nobreak  /PERCENT INTO pc_ /PRINT = YES /TIES = MEAN.
XSAVE OUTFILE = 'data.sav'.

SORT CASES BY pc_ (D).
SELECT IF pc_ <= !lowpc.
N OF CASES 1.
RENAME VARIABLE (!var = minval).
SAVE OUTFILE = 'minval.sav' /KEEP = nobreak minval.

GET FILE='data.sav'.
SELECT IF pc_ >= (!hipc).
SORT CASES BY pc_ (A).
N OF CASES 1.
RENAME VARIABLE (!var = maxval).
SAVE OUTFILE = 'maxval.sav' /KEEP = nobreak maxval.

MATCH FILES FILE = 'data.sav'
        /TABLE = 'minval.sav'
        /TABLE = 'maxval.sav'
        /BY = nobreak
        /DROP = nobreak.
COMPUTE !var_w = MAX(MIN(!var, maxval), minval).
EXECUTE.
DELETE VARIABLES pc_ minval maxval.
DATASET CLOSE DataSet1.
EXECUTE.
!ENDDEFINE.

!winsor var = roa lowpc = 1 hipc = 1.

Solution

  • In order to add a suffix to your new variable name you need to use the spss macro command !concat like this:

    COMPUTE !concat(!var,"_w") = MAX(MIN(!var, maxval), minval).
    

    In order to do this for a list of variables you can use a macro loop:

    define macrowithloop(vrs=!cmdend)
    !do !vr !in(!vrs)
        * do stuff.
        COMPUTE !concat(!vr,"_w") = MAX(MIN(!vr, maxval), minval).
        * other stuff.
    !doend
    !enddefine.
    
    macrowithloop vars=roa leverage roe lowpc .