Announcement

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

  • Removing characters from a variable label in a loop

    Hello,
    I'm attempting to add " (real)" to the end of the label of a group variables. So if for example, a variable has the label "Example", it will become "Example (real)"
    The following code already does this successfully for the variables vv1 vv2 vv3.

    Code:
    foreach v of vv1 vv2 vv3 {
     local l`v' : variable label `v'
      if `"`l`v''"' == "" {
       local l`v' "`v'"
     }
    }
        
        
    foreach v of var vv1 vv2 vv3 {
     label var `v' "`l`v'' (real)"
    }
    However, variable labels can't be longer than 80 characters, which becomes a problem for some of my variables as their labels are already close to this limit and adding " (real)" goes over it, resulting in nothing happening for those variables when I run the above loop.

    My desired solution would be to add an extra step where for labels with length superior to 73, it would only keep the first keep those first 73 characters, making space for the 7 characters in " (real)". This is something that I'm not being able to do, and thus I ask for your help. I'm also open to other solutions if you can think of something better.

    Thanks very much for your time.
    Hélder Costa

  • #2
    I am having difficulties seeing how close to or even more than 80 characters are very useful. I do not think that having two loops is necessary or makes the code more readable. Also, your code will fail for variables that already have a label attached.

    All these issues aside, you want something like

    Code:
    ...
    local label_real = usubstr(`"`l`v''"', 1, 73) + " (real)"
    label variable `v' `"`label_real'"'
    ...

    I will point to elabel (SSC, SJ, GitHub) that could replace the (double) loop

    Code:
    elabel variable (vv1 vv2 vv3) (=usubstr(@, 1, 73) + " (real)")

    Comment


    • #3
      Thank you daniel klein, I liked the elabel option!

      Comment

      Working...
      X