Announcement

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

  • How to use file name to rename variable

    Hi all, I have 750 different file(.dta) with same variable is date and Vol, so I need to use the name of this file to rename Vol variable to merge datasets. For example, I want to rename Vol to aaa with automatic ways. I would appreciate any suggestions how can I approach this problem in to-do files.
    Thanks for your suggestions.
    Click image for larger version

Name:	Capture.JPG
Views:	1
Size:	205.3 KB
ID:	1648131

  • #2
    Do you want to merge or append these 750 datasets?

    Comment


    • #3
      I want to merge these 750 datasets. And this image as follow, is the result i want to.
      Click image for larger version

Name:	Capture.JPG
Views:	1
Size:	207.2 KB
ID:	1648138


      Comment


      • #4
        Do the original file names all begin with 3 letters?

        Comment


        • #5
          It begins with 3 letters and ".csv". For example: "aaa.csv", "aam.csv",....
          Attached Files
          Last edited by Tan Nguyen; 03 Feb 2022, 08:39.

          Comment


          • #6
            Here's some syntax to get you started. I haven't tested this, so if I were you I'd experiment with one or two datasets first.

            Code:
            cls
            
            
            foreach name in .dta {
            
            ** Grabs the shapefile data we're interested in
            local files : dir "`c(pwd)'" files "*`name'*"
            
            foreach f of loc files { // loop through them all
            
            loc x: di  substr("`f'",1,3)
            
            qui {
            
            u `f', clear
            
            rename Vol `x'
            
            sa `f', replace // ONLY do this if it works
            
            }  // end qui
            } // end foreach f
            } // end foreach name
            What I do here is I loop through your files and grab the first three characters of your file and rename Vol to whatever those first three characters are.

            NOTE: if this were my problem, I'd save all of these as tempfiles in the last line and then merge them at the very end to whatever our master dataset is. I also presume these are the only datasets in your current directory
            Last edited by Jared Greathouse; 03 Feb 2022, 08:53.

            Comment

            Working...
            X