2015-10-11 49 views
1

我有一個目錄,其中有31個文件,我必須創建一些變量,然後加入它們。我正在嘗試通過一個循環,但我不能。有人能幫助我嗎?循環訪問目錄中的多個文件

cd "my dir" 
local allfiles: dir "my dir" files "*.dta" 
clear 

foreach f in `allfiles' { 

    use `f' 
    egen string_id = concat(ido idd) 
    sort string_id 
    by string_id: gen first = _n==1 

gen id = sum(first) 
drop first 

sort year id 
by year id: egen Value=sum(value) 
    by year id: egen Quantity=sum(quantity) 

save `mydata', replace 
append using `mydata' 
} 
+0

我已經標記了你的代碼。請記住在每行前加上4個空格。 –

+0

由於你的代碼明確,你不是真的想'加入'它們,而是'追加'它們。 –

回答

1

您的報告

我想通過一個循環,但我不能

是不是一個有用的一個。

請記住指出你面對的確切問題,即你得到什麼,你期望什麼,如果不明顯,爲什麼他們不一樣。

以下是工作代碼,假設您在示例目錄中有兩個內置auto數據集(使用sysuse auto加載它)的副本。

clear 
set more off 

// example directory with auto1.dta and auto2.dta 
cd "/home/roberto/Desktop/stata_tests/" 
local allfiles: dir "`c(pwd)'" files "*.dta" 

// create empty dataset to initiate appending 
tempfile mydata 
save "`mydata'", emptyok 

foreach f in `allfiles' { 

    // load data and do whatever 
    use "`f'", clear 
    gen source = "`f'" 

    // append first, then save 
    append using "`mydata'" 
    save "`mydata'", replace 
} 

// check 
keep make source 
sort make source 
list in 1/16, sepby(make) 

輸出:

. list in 1/16, sepby(make) 

    +---------------------------+ 
    | make    source | 
    |---------------------------| 
    1. | AMC Concord  auto1.dta | 
    2. | AMC Concord  auto2.dta | 
    |---------------------------| 
    3. | AMC Pacer  auto1.dta | 
    4. | AMC Pacer  auto2.dta | 
    |---------------------------| 
    5. | AMC Spirit  auto1.dta | 
    6. | AMC Spirit  auto2.dta | 
    |---------------------------| 
    7. | Audi 5000  auto1.dta | 
    8. | Audi 5000  auto2.dta | 
    |---------------------------| 
    9. | Audi Fox  auto1.dta | 
10. | Audi Fox  auto2.dta | 
    |---------------------------| 
11. | BMW 320i  auto1.dta | 
12. | BMW 320i  auto2.dta | 
    |---------------------------| 
13. | Buick Century auto1.dta | 
14. | Buick Century auto2.dta | 
    |---------------------------| 
15. | Buick Electra auto1.dta | 
16. | Buick Electra auto2.dta | 
    +---------------------------+ 

ssc describe fsssc describe filelist見。