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 December 23rd, 2014
I believe that for SPSS 22 you're asked (during the installation process) whether the Python Essentials should be installed as well. If you answered "no" to that question, then you'll have SPSS 22 without Python. In my case (Windows 8) I've a folder "C:\Program Files\IBM\SPSS\Statistics\22\Python" that holds "python.exe".
See if you can find something equivalent on your Mac, ok? If not, reinstalling SPSS may be the only option to get things working. If you're planning to do a considerable amount of work with SPSS it will be well worth the effort.
I'm not sure whether the student edition may have to do anything with the symptoms.
By Anon on December 23rd, 2014
I did select to install Python. I have the same folder you mentioned, in the same location.
By Ruben Geert van den Berg on December 23rd, 2014
And still even the test syntax does not run properly? If so, then perhaps post the issue here.
When Python is running properly, I'm sure the suffixing syntax will run fine too but if not, let me know, ok?
By Chloe on April 6th, 2015
This doesn't seem to work when the final rename variables string passed to SPSS is greater than 1024 (2^10) characters. I've tried it on all my large datasets and gotten errors. Any solutions for that?
By Martin Heine on October 26th, 2015
There is an easy method to do this using excel. Just simply copy the column with variable names to Excel. In Excel use the CONCATENATE command to add any text (e.g. Prefix_ or _Suffix) to the variable name. Now simply copy back the new variables names back to SPSS.