Announcement

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

  • Reanaming variables in folder

    Hi all,

    I have a series of .dta files named "city_data_year2000.dta","city_data_year2001.dta", ...,"city_data_year2009.dta" . I would like to rename all the variables except one called tech as t_var where t is represented by the year of the .dta, i.e. last numbers in the names of the .dta and then merge city_data_yeart with city_data_year2000t+5, so for instance city_data_year2000 with city_data_year2005, city_data_year2001 with city_data_year2006 until city_data_year2004 with city_data_year2009.

    I tried to write some code however I am stuck. Namely:

    Code:
    local myfilelist : dir "." files "city_data_year*.dta"
    
    foreach filename of local myfilelist {
     
        use "`filename'", clear
        local time substr("`filename'",-8,4)
        ds tech, not
        rename (`r(varlist)') ("`time'"_=)
    }
    This code raises an error, namely: parentheses unbalanced.
    Furthermore, without a local `time' I am unable to perform the merge.

    How can I do that?

    Thank you

  • #2
    Normally you wouldn't merge such files at all; you would append them. A wide layout with quite different variable names for different years creates more problems than it solves. That being so, I would do something more like this

    Code:
    local myfilelist : dir "." files "city_data_year*.dta"  
    
    foreach filename of local myfilelist {      
         use "`filename'", clear    
         local time = substr("`filename'",-8,4)      
         gen year = `time'      
         save, replace    
    }
    That aside, my guess is that you wanted to write

    Code:
      local time = substr("`filename'",-8,4)
    and
    Code:
    rename (`r(varlist)') (`time'_=)
    but that would be wrong because you can't start variable names with a number. So, if you really need what you're trying to do you need to put the year later in the variable name.
    Last edited by Nick Cox; 12 Jan 2023, 04:38.

    Comment


    • #3
      I see, thanks a lot

      Comment

      Working...
      X