Quantcast
Channel: Noodling in the data stream
Viewing all articles
Browse latest Browse all 48

Turn a date into Stata format quickly

$
0
0

There's a little program that's shown up more than once now in my housekeeping do-files, so it may be useful enough for a blog post, but it doesn't quite warrant a spot in c(sysdir_personal) as a stand-alone ado-file. Here:


// turn this date to Stata format
// if it's not that way already
capture prog drop setStataDate
program setStataDate

args v fmt // fmt can be MDY or YMD
capture confirm string variable `v'
if _rc==0 {
   local l`v' : variable label `v'
   gen x=date(`v',"`fmt'")
   format x %td
   drop `v'
   rename x `v'
   label variable `v' "`l`v''"
   order `v'
}

end

I use it with data sets derived from merging other data sets. It's useful if in the original data sets there are string dates in mixed formats -- maybe YYYY-MM-DD in the "master", and MM/DD/YYYY in the "using" -- or if these string dates have labels I want to keep. So, you see why it's not clear that this is worth an ado-file. I don't want to type all the code between the curlies more than once, but usually I don't have to.

I do want to be able to call this program by name, as in setStataDate somedate MDY from within another program, then forget about it, safe in the knowledge that it won't make any difference if somedate is already in Stata format. That's the job of the if-condition you see there, and this is all this little program does.


Viewing all articles
Browse latest Browse all 48

Trending Articles