Announcement

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

  • Local macro returns variable name and subscript rather than value

    Hi Statalist,

    I am trying to rename a set of variables in Stata 16.1. The new variable name I want to use is stored across three observations, and I want to combine them into a variable name. I've written some toy code below to test my proposed approach.

    Code:
    clear all
    
    * toy dataset
    set obs 3
    
    gen v1 = ""
    
    replace v1 = "part" in 1
    replace v1 = "of" in 2
    replace v1 = "varname" in 3
    
    list
    
    * proposed code for renaming
    
    local p1 v1[1]
    local p2 v1[2]
    local p3 v1[3]
    
    di `p1' `p2' `p3'
    
    rename v1 `p1'_`p2'_`p3'
    However, this code fails to rename the variables to what I want. I receive the following error

    Code:
    1 new variable name invalid
        You attempted to rename v1 to v1[1]_v1[2]_v1[3].  That is an invalid Stata variable name.
    r(198);

    The reason seems to be because the local macros p1 p2 p3 output the variable name with explicit subscript e.g. v1[1] rather than the actual underlying value e.g. "part". Weirdly, however the display command correctly outputs the values stored in each observation.

    How I can I get the local macro to pass the values stored in v1[1] v1[2] and v1[3] to the rename command rather than just the variable names?

    Thanks in advance,

    Dan

  • #2
    A macro in stata is just a place to store a string. If you define the macro without an equal sign it will just store whatever you put after the name as a string, i.e. it will not evaluate that. display will evaluate anything you give it.

    Code:
    . local foo 1 + 3
    
    . di `foo'
    4
    
    
    . di "`foo'"
    1 + 3
    So the local `foo' contains the string 1 + 3. If you type di `foo', then Stata sees di 1 + 3 and thinks "I know what 1+3 is, it is 4" (Stata is smart, about as smart as my 4 year old son), so it shows 4. However, if we ask Stata to display the string contained in the local macro `foo', it shows what that string really contains: "1 + 3".

    The easiest solution is to define the local macros with the equal sign. This will force Stata to evaluate what comes after the equal sign and put the result in the local macro.
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      Your solution works very well. Thanks very much.

      Comment

      Working...
      X