Suffix string from all variable names in SPSS

I have a data set in which each variable name has the suffix "_1" (this was done to indicate the first polling time point). I want to remove this suffix from all the variables, but there are hundreds of them, so I'm looking for a way to do this without using the RENAME statement hundreds of times.

The closest to the relevant information I found was from the link below: "Several SPSS loops for dynamic variable renaming." However, these examples show how to add a suffix or change a prefix but not remove a suffix.

http://www.ats.ucla.edu/stat/spss/code/renaming_variables_dynamically.htm

I have the Essential Python package installed with SPSS, although I am not familiar with Python.

+4
source share
3 answers

I do not know about SPSS. A quick search showed the example “Renaming variables using Python” using python ( http://www.ats.ucla.edu/stat/spss/faq/renaming_vars_Python.htm )

It would fit in your case with a small change:

begin program.
import spss, spssaux
spssaux.OpenDataFile('d:\data\elemapi2.sav')
vdict=spssaux.VariableDict()
mylist=vdict.range(start="grad_sch", end="enroll")
nvars = len(mylist)

for i in range(nvars):
    myvar = mylist[i]
    mynewvar = myvar.strip("_1")
    spss.Submit(r"""
        rename variables ( %s = %s) .
                        """ %(myvar, mynewvar))
end program.
+1
source

Here's a slightly denser version of the Jignesh Python program. It is functionally the same.

begin program.  
import spss, spssaux  
filteredvarlist=[v.VariableName for v in spssaux.VariableDict(pattern="^.*_1$")]  
spss.Submit( "rename variables (%s=%s)." %  
    ("\n".join(filteredvarlist), "\n".join([v[:-2] for v in filteredvarlist]))  
)  
end program.
+2
source

, - UCLA, / , python, , .

, "V01_1".strip("_1") "V0", - "V_1_1".strip("_1") "V", , .

, RENAME VARIABLES, "_1" ( , , ).

, RENAME VARIABLE , , , RENAME VARIABLES? , , , :

DATA LIST FREE / ID V01_1 V02_1 V03_1 W_1_1 W_2_1 W_3_1.
BEGIN DATA
0 11 12 13 21 22 23
END DATA.

begin program.
spss.Submit(r"set mprint on.")
import spss, spssaux
allvarlist=[str(v) for v in spssaux.VariableDict()]
filteredvarlist=[v for v in allvarlist if v.endswith("_1")]
spss.Submit( "rename variables (\n" \
     + "\n".join(filteredvarlist) \
     + "\n=\n" \
     + "\n".join([v[:-2] for v in filteredvarlist]) \
     + ").")
spss.Submit(r"set mprint off.")
end program.
0

Source: https://habr.com/ru/post/1624341/


All Articles