Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Shorten variable labels

    I have a set of variables, generated using the separate command with the shortlabel option. The variable labels are shown below. What I want to do, in an automated fashion, is delete the string "student_ethnicity == " from every variable label. Thanks for any suggestions....

    storage display value
    variable name type format label variable label
    ----------------------------------------------------------------------------------------------------------------------------
    z_score1 float %9.0g student_ethnicity == Asian
    z_score2 float %9.0g student_ethnicity == Black
    z_score3 float %9.0g student_ethnicity == Hispanic
    z_score4 float %9.0g student_ethnicity == NativeAmer
    z_score5 float %9.0g student_ethnicity == White



  • #2
    You can do so using extended macro functions to get the variable label and then process that string. You can also do this in one line, but it makes for a little harder reading for didactic purposes.

    Code:
    foreach v of varlist z_score? {
        local old_vlbl : var lab `v'
      local new_vlbl = subinstr(`"`old_vlbl'"', " student_ethnicity == ", "", 1)
      label var `v' `"`new_vlbl'"'
    }

    Comment


    • #3
      Here are solutions based on community-contributed commands that implement the loop shown in #2

      1. labnoeq (from labutil, SSC)

      Code:
      labnoeq z_score*
      2. labvarch (labutil, SSC)

      Code:
      labvarch z_score* , after("== ")
      3a. elabel (SSC)

      Code:
      elabel variable (z_score*) (= substr(@, strpos(@, "= ")+2, .))
      3b. elabel (SSC)

      Code:
      elabel variable (z_score*) (= subinstr(@, "student_ethnicity == ", "", .))
      Last edited by daniel klein; 17 May 2021, 11:59.

      Comment


      • #4
        Code:
        foreach v of varlist z_score? {
        
                 label var `v' `=word("`: var lab `v' '", -1)'
        }

        Comment


        • #5
          #4 is a nice and short solution if we are willing to assume that the equals signs are followed by exactly one word.

          Sorry for the repeated advertisement but the elegance of this solution (given the assumption holds) translates directly to elabel making it almost less awkward to type than the original code:

          Code:
          elabel var (z_score?) (=word(@, -1))

          Comment

          Working...
          X