簡體   English   中英

如何在Stata中循環合並多個數據集?

[英]How to do a loop merging multiple datasets in Stata?

我正在嘗試創建兩個文件列表並創建兩個合並所有這些文件的新數據集。 為此,我嘗試了以下操作:

*** SET FOLDER PATHS ***********************************************************
    global projectFolder  "C:\Users\XXX"
    global codeFolder     "${projectFolder}\code"
    global databaseFolder "${projectFolder}\data"
    global rawFolder      "${databaseFolder}\raw"
    global outputsFolder  "${databaseFolder}\output"
    
*** CREATING VECTORS WITH FILE NAMES *******************************************
global file_all        dir "$outputsFolder" files "*.dta"
di `$file_all' 

global file_monthly    dir "$outputsFolder" files "*_monthly.dta"
di `$file_monthly' 

global file_yearly :  list global file_all - global file_monthly
di `$file_yearly' 

我發現了一些問題。 首先,我無法創建文件列表,其次,如果不合並兩次第一個數據集,我找不到創建此循環的方法。

*** MERGING YEARLY OUTCOMES ****************************************************
use "$outputsFolder\first_dataset.dta", clear


    foreach file in `file_yearly' {
         merge 1:1 muni_code year using `file', nogen
    }

在文件的foreach循環中,您可以有條件地加載/使用第一個文件(在下面的示例中,它需要知道“第一個”文件的名稱),否則合並,如下所示:

local files: dir "." files "yearly*.dta"
foreach f of local files {
    if "`f'" == "yearly_1.dta" use `f'
    else merge 1:1 year muni using `f', nogen
}
list, clean

Output:

       year   muni       val1       val2       val3  
  1.   2001      1   .3132002   .1924075   .8190824  
  2.   2002      2   .5559791   .1951401   .4882096  
  3.   2003      3   .9382851   .9509598   .2704866  
  4.   2004      4   .7363221   .2904454   .5859706 

輸入:

set seed 123
forvalues i = 1/3 {
    clear
    set obs 4
    gen year = 2000 + _n
    gen muni = _n
    gen val`i' = runiform()
    save yearly_`i', replace
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM