Skip to Main Content

A few SPSS loops for renaming variables dynamically | SPSS Code Fragments

On this page, we show a few SPSS loops for dynamically renaming
variables.  The following are code fragments intended for use by more advanced
SPSS users.  Although they may look complex, only small changes are needed to
adapt these loops for your data.
In these examples, we modify only the first few of the names, but you can rename
all of them by modifying the !rename command.

Scenario number 1

We have a list of variables and a list for the new names of these variables.
In the example below, we want to rename variables faminc1 and faminc2
to be a and b for no particular reason.

data list free 
/famid faminc1 to faminc12.
begin data
1 3281 3413 3114 2500 2700 3500 3114 -999 3514 1282 2434 2818
2 4042 3084 3108 3150 -999 3100 1531 2914 3819 4124 4274 4471
3 6015 6123 6113 -999 6100 6200 6186 6132 -999 4231 6039 6215
end data.
define !rename1 (olist = !charend('/')
                        /nlist=!cmdend )
!let !rest = !nlist
!do !vname !in (!olist) 
!let !nname=!head(!rest)
!let !rest = !tail(!rest)
rename variables (!vname = !nname).
!doend
!enddefine.

!rename1 olist = faminc1 faminc2
              /nlist = a b .
Image code_loops_1

Scenario number 2

We have a list of variables, and the name for each variable consists of the
original name plus a common suffix.  For example, we are going to rename variables
faminc1 faminc2 and faminc3 to be faminc1_new, faminc2_new
and faminc3_new
below.

data list free 
/famid faminc1 to faminc12.
begin data
1 3281 3413 3114 2500 2700 3500 3114 -999 3514 1282 2434 2818
2 4042 3084 3108 3150 -999 3100 1531 2914 3819 4124 4274 4471
3 6015 6123 6113 -999 6100 6200 6186 6132 -999 4231 6039 6215
end data.

define !rename2 (vlist = !charend('/')
                        /suffix=!cmdend )
!do !vname !in (!vlist) 
!let !nname = !concat(!vname, !suffix)
rename variables (!vname = !nname).
!doend
!enddefine.

!rename2 vlist = faminc1 faminc2 faminc3
              /suffix = _new .

Image code_loops_2

Scenario number 3

We have a list of variables defined by a prefix followed by an index number.  We are going to change the prefix and still use the same index order.  For
example, we are going to rename variables faminc1–faminc5 to be
test1–test5.

data list free 
/famid faminc1 to faminc12.
begin data
1 3281 3413 3114 2500 2700 3500 3114 -999 3514 1282 2434 2818
2 4042 3084 3108 3150 -999 3100 1531 2914 3819 4124 4274 4471
3 6015 6123 6113 -999 6100 6200 6186 6132 -999 4231 6039 6215
end data.

define !rename3 (oldprefix = !charend('/')
                        /newprefix=!charend('/')
                        /n = !cmdend )
!do !var = 1 !to !n
   !let !oldname = !concat(!oldprefix, !var)
   !let !newname = !concat(!newprefix, !var)
   rename variables (!oldname = !newname).
!doend
!enddefine.

!rename3 oldprefix = faminc
              /newprefix  = test
              /n=5 .
Image code_loops_3