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 Kate on October 25th, 2014
This doesn't work. Like at all.
By Ruben Geert van den Berg on October 26th, 2014
I just retested the syntax and it runs fine on my system. Are you sure you have the SPSS Python Essentials properly installed an running? This syntax needs them in order to run (and perhaps this tutorial should be more explicit on that).
If things still don't work after doing so, please provide us with some more detail regarding the error message you get, OK?
By Anon on December 22nd, 2014
I'm running SPSS 22 on a Mac and am getting an error - _SLINE OFF. What does this mean?
By Ruben Geert van den Berg on December 22nd, 2014
"_SLINE OFF." usually means that there's some unclosed control structure (LOOP, DO IF, DO REPEAT) somewhere in your syntax. I don't think it's related to you working on a Mac. Are you sure it's this Python block that triggers the error? And are you sure that Python is running properly from within SPSS as well?
By Anon on December 22nd, 2014
Thanks, Ruben.
Here is my syntax:
begin program.
import spssaux
for var in spssaux.GetVariableNamesList():
print var
end program.
This is actually SPSS's suggested code to ensure
that Python is running correctly - so apparently it isn't. I read that SPSS 22 (I have student edition) comes with Python Essentials already installed, and I don't want to reinstall SPSS. What do you suggest I do?