Announcement

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

  • [HELP] Appending dta files and generatinig filename variable

    Hello Statalist--

    Currently appending several dta files together and came up with the following code

    Code:
    clear
    fs *.dta
    
    use .dta
    local getfile "append using "
    foreach file in `r(files)' {
        `getfile' `file'
    }
    However I want to add a variable that reflects the original filename of the source. I know this can be done with the generate(newvar) command but not too sure where in my loop it would go? Any help will be greatly appreciated!

  • #2
    The local macro getfile serves no real purpose here and it makes it harder to understand what the code is doing. Also, do you really have a file named .dta to start this process off with? Since I'm not comfortable with the code you have, I'm going to go a slightly different route.
    Code:
    local filenames: dir "." files "*.dta"
    clear
    gen source = ""
    foreach f of local filenames {
       append using `"`f'"'
       replace source = `"`f'"' if missing(source)
    }
    Added: This code assumes that the files being appended together do not contain any variable named source. If that's not the case, pick a different name for the variable that own't clash with anything in the .dta files.

    Comment

    Working...
    X