Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax to loop variable recode in SPSS

I'm new to using syntax and need help recoding a long series of variables into new variables.

Essentially the bit of code I am trying to loop is:

RECODE cqC2_1_11 (9 thru Highest=10) (ELSE=COPY) INTO cqC2_1_11_T3.
VARIABLE LABELS  cqC2_1_11_T3 ‘CQC2Top3Box’.
EXECUTE.

I need to do that for variables cqC2_1_11 thru cqC2_21_415 (these variables are all sequentially next to each other).

If it's too complex to recode into a new variable because I need to specify each new variable name, I can simply recode into the same variable and save a new copy of the dataset for the analysis I need to run.

like image 525
Chad Avatar asked Jan 18 '26 12:01

Chad


1 Answers

Firstly, RECODE command can take in (and output) multiple variables. See the documentation and the example provide here. Though the first example provides in that link recodes into the same variables, an equivalent command to recode into different variables would be:

RECODE V1 TO V3 (0=1) (1=0) (2,3=-1) (9=9) (ELSE=SYSMIS) INTO W1 to W3.

The above works because it is intutive for SPSS to interpret and expand out W1 TO W3 to equal W1, W2, W3.

The difficulty you have, although SPSS can read sequential variables cqC2_1_11 TO cqC2_21_415 as they are input existing variables in the dataset, it is not easy to specify equivalent matching output variable names.

For example, you could not simply specify RECODE....INTO T3B_cqC2_1_11 TO T3B_cqC2_21_415 as you have double indexing occurring and SPSS would not know exactly how to expand out those names.

If however, for example you had cqC2_1 TO cqC2_415 i.e. 415 variables you could use RECODE....INTO T3B_cqC2_1 TO T3B_cqC2_415.

So your best option is to build a custom macro, using either SPSSs build in macro facility or its integrated python programmability.

Python programmability is far superior so below is python solution you can adapt for your specific needs and criteria, to help you get started:

get file="C:\Program Files\IBM\SPSS\Statistics\23\Samples\English\Employee data.sav". 

begin program.
import spss, spssaux, spssdata
spss.Submit("set mprint on.")
vd=spssaux.VariableDict(pattern="job")

spss.Submit("""RECODE %s (8 THRU HI=1) (ELSE=COPY) INTO %s.""" % ("\n".join([str(v) for v in vd]),"\n".join(["T3B_" + str(v) for v in vd])))
for v in vd:
    spss.Submit("""VARIABLE LABEL T3B_%s "%s".""" %(v, "T3B_" + v.VariableLabel))
spss.Submit("set mprint off.")
end program.
like image 160
Jignesh Sutar Avatar answered Jan 21 '26 03:01

Jignesh Sutar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!