Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

Stata: looping and appending

I have a situation where I need to import all the files in a directory and append them. My code is this

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
}
}

However when I use this code it seems to run an extra loop (* forval k =1/`n'*) that create duplicate entries. I cannot get rid of that code since I need it for the append command. I was wondering whether there is a way to mitigate this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The double loop is causing the problem:

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

You don't use the tokens created by tokenize, so you can drop it.

Shorter would be:

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

You might want to read help quotes if for some reason you have "weird" file names (and because it's a good read anyway).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...