SPSS Statistics

 View Only
Expand all | Collapse all

Systematically rename variables using their labels

  • 1.  Systematically rename variables using their labels

    Posted Wed March 27, 2024 12:49 PM

    Hello,

    I have a large number of variables I want to rename using their labels. For example, I have V1, V2, and V3 with labels "Number of Laps," "Time to Complete," and "Age," respectively. Is there a way to systematically rename V1 to V3 by referencing their labels WITHOUT spelling out what the specific names should be? E.g., I want to rename V1 = Number_of_Laps, but I don't want to specify "Number_of_Laps," instead just referencing "V1's label, whatever it may be."

    Thanks!

    Alexa



    ------------------------------
    Alexa B
    ------------------------------


  • 2.  RE: Systematically rename variables using their labels
    Best Answer

    IBM Champion
    Posted Wed March 27, 2024 01:51 PM

    Bear in mind that variable labels are not necessarily valid as variable names even ignoring the space issue.  They might also be duplicates, since labels don't have to be unique.  And some variables might not have labels or some labels might conflict with existing variable names.

    However, ignoring those issues, you can do the renaming like this.

    begin program python.
    import spssaux

    vardict = spssaux.VariableDict("V1 to V3")
    for v in vardict:
        vlabel = v.VariableLabel.replace(" ", "_")
        if vlabel:
            spss.Submit(f"""RENAME VARIABLES ({v.VariableName} = {vlabel})""") 
    end program.

    If  you want to rename all labelled variables, just omit "V1 to V3" above.



    ------------------------------
    Jon Peck
    ------------------------------