循环访问目录中的多个文件

loop to access multiple files in a directory

我有一个包含 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' 
}

您的报告

I am trying through a loop but I can not

不是有用的。

请记住具体说明您面临的具体问题,即您得到了什么、您期望什么,如果不明显,请说明它们为何不同。

下面是工作代码,假设您在示例目录中有两个内置 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