Announcement

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

  • Rename a variable with content

    Hello,

    I would like to rename a variable (suppose it's name is VAR) with the content that is in a specific observation (let's say A[3] has the name of a city).
    So, I want he name of VAR to be the name of the city in A[3].
    My only idea was the following command:
    rename (VAR) (A[3])

    I know that to replace the content of VAR with the content of A[3] I can use
    replace VAR = A[3]

    But I want the name of VAR equal to the content of A[3].

    Can someone help me?

  • #2
    Welcome to Statalist.

    Below I present code that does what you ask, and demonstrates a problem with your request. It is not the case that every city name is an acceptable Stata variable name, and I use the strtoname() function to turn A[3] into an acceptable Stata variable name.
    Code:
    cls
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input float VAR str20 A
    101 "whatever"
    102 "whatever"
    103 "New York"
    104 "whatever"
    105 "whatever"
    end
    
    local city = A[3]
    local name = strtoname(A[3])
    * this won't work
    rename VAR `city'
    * this won't work
    rename VAR "`city'"
    * this will work
    rename VAR `name'
    list, clean noobs
    Code:
    . local city = A[3]
    
    . local name = strtoname(A[3])
    
    . * this won't work
    
    . rename VAR `city'
    syntax error
        Syntax is
            rename  oldname    newname   [, renumber[(#)] addnumber[(#)] sort ...]
            rename (oldnames) (newnames) [, renumber[(#)] addnumber[(#)] sort ...]
            rename  oldnames              , {upper|lower|proper}
    r(198);
    
    . * this won't work
    
    . rename VAR "`city'"
    syntax error
        Syntax is
            rename  oldname    newname   [, renumber[(#)] addnumber[(#)] sort ...]
            rename (oldnames) (newnames) [, renumber[(#)] addnumber[(#)] sort ...]
            rename  oldnames              , {upper|lower|proper}
    r(198);
    
    . * this will work
    
    . rename VAR `name'
    
    . list, clean noobs
    
        New_York          A  
             101   whatever  
             102   whatever  
             103   New York  
             104   whatever  
             105   whatever

    Comment


    • #3
      Thank you! It worked perfectly.

      Comment

      Working...
      X