Announcement

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

  • using "subinstr" for labels in a loop

    Hello,

    I have a data set with a number of variable labels that I would like to change in a loop. The variable labels have the text "${g0yx}" which I would like to replace with "crop". Please see example below:

    What I have now:
    Var 1 label: How much ${g0yx} was saved for seed?
    Var 2 label: How much ${g0yx} was sold for seed?

    What I want to have:
    Var 1 label: How much crop was saved for seed?
    Var 2 label: How much crop was sold for seed?

    The code I have right now is:

    foreach i of varlist * {
    local a : var label `i'
    local a = subinstr("`a'","${g0yx}","crop",.)
    label var `i' "`a'"
    }


    When I run that code, the "${g0yx}" is removed but is not replaced with "crop". Any suggestions on how to fix this?

    Many thanks,
    Jowel



  • #2
    The problem you are having arises from the $ character. Stata interprets that as the beginning of a reference to a global macro, not as a literal dollar sign. The fact that you are inside a loop has nothing to do with it. You can get around that by modifying your code as follows:

    Code:
    // FIRST CREATE A DEMONSTRATION DATA SET
    clear
    set obs 1
    gen var1 = 123
    label var var1 "How much \${g0yx} was saved for seed?"
    
    //    HERE'S THE CODE THAT SOLVES THE PROBLEM
    local a: var label var1
    local a: subinstr local a "\${g0yx}" "crop", all
    display `"`a'"'
    label var var1 `"`a'"'
    des
    Note another key to success here: using the local macro function -subinstr-, rather than the -gen- function -subinstr()-.

    Comment


    • #3
      Thank you very much Clyde, this worked!

      Comment

      Working...
      X