Announcement

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

  • Removing Single Quotes from Variable Label

    I am trying to clean up variable labels - removing spaces and punctuation - in anticipation of turning them into variable names.

    When I try to remove single quotes using the following code, I get an error of "too few quotes" and "invalid syntax". Any advice/assistance would be so helpful

    Code:
    foreach var of varlist * {
     local lab `: var label `var''
     
     if length("`lab'") > 80 {
      local lab `: di substr("`lab'", 1, 79)'
     }
     
     local lab `: di subinstr("`lab'", "%", "Pct",.)'
     local lab `: di subinstr("`lab'", "'", "",.)'
     local lab `: di subinstr("`lab'", ":", "",.)'
     
     label var `var' "`lab'"
    }
    Best,
    Erika

  • #2
    I don't understand the check here, as no variable label can be longer than 80 characters.

    There's a function str2name() that will do this for you, but as an example I would try

    Code:
    foreach var of varlist * {    
        local lab : var label `var'    
        local lab = subinstr(`"`lab'"', "%", "Pct",.)    
        label var `var' `"`lab'"'  
    }

    Comment


    • #3
      Nick posted while i was writing. Implicit in his answer is the need for compound double quotes whenever a string may contain embedded single quotes. For more information, closely read the output of help quotes.

      Here's the way I reworked the code in post #1, changing the length check from 80 to 8 for demonstration purposes.
      Code:
      foreach var of varlist testvar {
       describe `var'
       local lab : variable label `var'
       display _newline `"lab: `lab'"'
       local llen : strlen local lab
       if `llen' > 8 {
        local lab = substr(`"`lab'"', 1, 8)
        display _newline `"lab after substr: `lab'"'
       }
       local nlab : subinstr local lab `"'"' "", all
       display _newline `"nlab: `nlab'"'
       label var `var' "`nlab'"
       describe `var'
      }
      Code:
                    storage   display    value
      variable name   type    format     label      variable label
      -------------------------------------------------------------------------------------------------
      testvar         str1    %9s                   abc'defghijklm
      
      lab: abc'defghijklm
      
      lab after substr: abc'defg
      
      nlab: abcdefg
      
                    storage   display    value
      variable name   type    format     label      variable label
      -------------------------------------------------------------------------------------------------
      testvar         str1    %9s                   abcdefg
      
      .

      Comment

      Working...
      X