Stata:循环和追加

Stata: looping and appending

我有一种情况需要导入目录中的所有文件并追加它们。我的代码是这样

local files : dir "C:\Users\xx" files "*.xls"

local n: word count `files'
tokenize ``files''

cd "C:\Users\xx"

forval  k =1/`n'{

foreach file in `files' {
    import excel "`file'", sheet("Time Sheet") clear

drop in 3

if `k' == 1 {
    di in red `k'
        save "C:\Users\xx\master.dta", replace
    }
    else {
    append using "C:\Users\xx\master.dta"
    }
    save "C:\Users\xx\master.dta", replace
}
}

然而,当我使用此代码时,似乎 运行 一个额外的循环 (* forval k =1/`n'*) 创建了重复的条目。我无法删除该代码,因为附加命令需要它。我想知道是否有办法缓解这个问题。

双循环导致问题:

local files : dir "D:/Datos/rferrer/Desktop/statatemps" files "test*.xls"

cd "D:/Datos/rferrer/Desktop/statatemps"

local counter = 1
foreach file in `files' {

    import excel "`file'", sheet("Hoja1") firstrow clear

    if `counter' == 1 {
        di in red `counter'
        save "D:/Datos/rferrer/Desktop/statatemps/master.dta", replace
    }
    else {
        append using "D:/Datos/rferrer/Desktop/statatemps/master.dta"
        save "D:/Datos/rferrer/Desktop/statatemps/master.dta", replace
    }

    local counter = 0
}

list

您不使用 tokenize 创建的令牌,因此您可以放弃它。

更短的是:

clear
set more off

local pathdir "D:/Datos/rferrer/Desktop/statatemps"

local files : dir "`pathdir'" files "test*.xls"

save "`pathdir'/master.dta", emptyok replace
foreach file in `files' {

    import excel "`file'", sheet("Hoja1") firstrow clear
    append using "`pathdir'/master.dta"
    save "`pathdir'/master.dta", replace

}

list

如果出于某种原因您有 "weird" 个文件名(并且因为它无论如何都很好读),您可能想阅读 help quotes