Question
“I have a data file in which all variables were measured in 2012. I'd like to suffix their names with "_2012". What's the easiest way to do this?”
SPSS Python Syntax Example
begin program.
variables = 'v5 to v10' #Specify variables to be suffixed.
suffix ='_2012' # Specify suffix.
import spss,spssaux
oldnames = spssaux.VariableDict().expand(variables)
newnames = [varnam + suffix for varnam in oldnames]
spss.Submit('rename variables (%s=%s).'%('\n'.join(oldnames),'\n'.join(newnames)))
end program.
variables = 'v5 to v10' #Specify variables to be suffixed.
suffix ='_2012' # Specify suffix.
import spss,spssaux
oldnames = spssaux.VariableDict().expand(variables)
newnames = [varnam + suffix for varnam in oldnames]
spss.Submit('rename variables (%s=%s).'%('\n'.join(oldnames),'\n'.join(newnames)))
end program.
Description
- This syntax will add a suffix to one, many or all variables in your data.
- Variable names can be specified right behind
variables =
. - Following SPSS Syntax conventions, variable names should be separated by spaces. The TO and ALL keywords may be used and the entire specification should be enclosed in quotes (''). The desired suffix should be enclosed in quotes as well.
- Next, a suffix can be specified right behind
suffix =
. - As a test file for this solution, you could use supermarket.sav.
THIS TUTORIAL HAS 15 COMMENTS:
By Ruben Geert van den Berg on October 27th, 2015
Thanks for your comment! We're well aware of such methods and we often used them in the past ourselves. However, we rather avoid them because they cost too much time and require extra software (Excel in this case) that not all SPSS users may have installed.
Last but not least, the Python approach is way more replicable: if you'd like to pull the same trick on other sets of variables or different data files, there's no need to mess around with Excel each time you'd like to do so.
By Jens on October 27th, 2015
Great Tutorial! Totally works but can you help me and create a prefix as well? I couldn't do it :(
By Ruben Geert van den Berg on October 28th, 2015
Sure! I uploaded a tiny syntax example here. Hope that helps!
By Jennifer on October 30th, 2015
I ran this syntax and it worked but now when I type in my syntax window SPSS is very slow to respond and my text appears as plain text (small black letters) before switching to the SPSS syntax color coding. Is there a reason it would be responding like this?
By Ruben Geert van den Berg on October 30th, 2015
Thanks for your comment! However, I haven't seen any such symptoms myself. My experience is that SPSS sometimes gets slow when running huge (I mean: huge) jobs repetitively.
This is resolved by saving all work and "killing" SPSS via Windows task manager. Upon restarting SPSS, everything is back to normal again. So the only suggestion that comes to mind right now is to give that a shot as well.