Announcement

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

  • How to use file name in a loop to rename variable

    Hi all, I need to use the name of the file to rename variables. I have multiple files that have common variable (v5). I need to rename v5 to filename to specify the variable. Here is my example:
    Code:
    cd "D:\Users\Admin\Desktop\Test-STATA"
    
    clear
    local files : dir "D:\Users\Admin\Desktop\Test-STATA" files "*.dta"
    foreach file of local files {
    insheet using "`file'"
    local outfile = subinstr("`file'",".dta","",.)
    rename v5 `outfile'
    save "`outfile'", replace
    }
    But the result doesn't seem work
    Code:
    . cd "D:\Users\Admin\Desktop\Test-STATA"
    D:\Users\Admin\Desktop\Test-STATA
    . clear
    . local files : dir "D:\Users\Admin\Desktop\Test-STATA" files "*.dta"
    . foreach file of local files {
      2. insheet using "`file'"
      3. local outfile = subinstr("`file'",".dta","",.)
      4. rename v5 `outfile'
      5. save "`outfile'", replace
      6. }
    (2 vars, 6 obs)
    variable v5 not found
    r(111);
    
    end of do-file
    
    r(111);
    Here is my folder with file name. Can anyone tell me that what's wrong with my code? Thank you all !!!
    Click image for larger version

Name:	Capture.PNG
Views:	1
Size:	62.2 KB
ID:	1650883

  • #2
    I think the problem is that the variable v5 has not been found in some files.

    Comment

    Working...
    X