Stata:循环和追加 [英] Stata: looping and appending

查看:8
本文介绍了Stata:循环和追加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

local files : dir "C:Usersxx" files "*.xls"

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

cd "C:Usersxx"

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:Usersxxmaster.dta", replace
    }
    else {
    append using "C:Usersxxmaster.dta"
    }
    save "C:Usersxxmaster.dta", replace
}
}
但是,当我使用这段代码时,它似乎运行了一个额外的循环(*forval k=1/`n‘*),从而创建了重复的条目。我无法删除该代码,因为我需要它来执行append命令。我想知道是否有办法缓解这个问题。

推荐答案

双循环导致问题:

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

如果由于某种原因,您的文件名"奇怪"(而且无论如何都很好读),您可能需要阅读help quotes

这篇关于Stata:循环和追加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆