Announcement

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

  • Looping over sub-folders in a folder, identifying .dta files in all sub-folders, and extracting particular variables

    Hi,
    I am a new user of STATA. I have 32 sub-folders, and each sub-folder contains files of different types including .dta. I need to extract only a few variables from these .dta files of all sub-folders. Could you please guide me through how could I do that? Thanks.

  • #2
    Here is a sketch of a solution. This is pretty advanced code for a new user of Stata. The relevant help files are help macro and help foreach. How you want to combine the data in one dataset depends on your exact problem, which you did not tell us. You can look at help merge and help append.

    Code:
    local vars "id v1 v2 v42"
    local root "c:\wherever_your_data_is_stored"
    local dirs : dir "`root'" dirs *
    foreach dir of local dirs {
        cd "`root'/`dir'" // watch out! the directories MUST be conntect with / not \
        local files : dir . "files" *.dta
        foreach file of local files {
            use `vars' using "`file'"
            // either use -merge- or -append- depending on the exact problem
        }
    }
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment

    Working...
    X