Announcement

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

  • Removing numbers from variable labels in loop

    Hi,

    I am trying to remove all numbers from values levels (e.g. 1yes 2no) using the following, but it's showing "Invalid name:

    Code:
    foreach var of varlist * {
        label val `var'
        local newlabel : subinstr local label "0-9" ""
        label val `var' "`newlabel'"
    }
    Can you please suggest what might be wrong with method.

    Thank you!

  • #2
    Perhaps this will start you in a useful direction. This assumes that the value label numbers are as you showed them.
    Code:
    // these are example labels for demonstrating
    label list
    
    // the work starts here
    label dir
    local labels `r(names)'
    macro list _labels
    
    numlabel `labels', remove mask(#)
    label list
    Code:
    . // these are example labels for demonstrating
    . label list
    yn:
               0 0no
               1 1yes
    zoo:
               1 cat
               2 dog
    
    . 
    . // the work starts here
    . label dir
    yn
    zoo
    
    . local labels `r(names)'
    
    . macro list _labels
    _labels:        yn zoo
    
    . 
    . numlabel `labels', remove mask(#)
    
    . label list
    zoo:
               1 cat
               2 dog
    yn:
               0 no
               1 yes
    
    .

    Comment


    • #3
      From the title and the post in #1 it is not clear whether the problem is with variable labels or value labels. The solution in #2 assumes the problem is with value labels.

      I will assume that the problem is with variable labels.

      The suggested code

      Code:
      label val `var'
      will detach the value label, if any, from the variables `var'. That does not help. A better approach might be

      Code:
      local label : variable label `var'
      That code will put the variable label of `var' into the local macro label.

      The suggested code

      Code:
      local newlabel : subinstr local label "0-9" ""
      will remove the string literal "0-9" from the variable label obtained in the first step. That does not help. A better approach might be

      Code:
      local newlabel = ustrregexra(`"`label'"', "^[0-9]+[ ]*", "")
      The code

      Code:
      label val `var' "`newlabel'"
      tries to attach "`newlabel'" as a value label to `var'. [Edit: btw. this what is causing the invalid name error]. A better approach might be

      Code:
      label variable `var' `"`newlabel'"'
      which attaches "`newlabel'" as a variable label to `var'.
      Last edited by daniel klein; 10 Feb 2023, 05:35.

      Comment

      Working...
      X