The Virtue of Laziness: -append- and -replace- with big loops

When you’re running large production jobs in Stata (or whatever) that involve iterative runs (perhaps over a set of files, or subsets of data, or files representing subsets of data…), it’s useful to produce files containing summary stats, parameter estimates, metadata, etc.

You can do this with the -log- and -cmdlog- commands, and I’m very fond of Stata’s -file’ commands.

You run into problems, however, when deciding whether to ‘append’ or ‘replace’ your logs and output files. You could write one set of commands for your first iteration with the ‘replace’ option, and a separate set for the 2nd…nth iterations, but that’s painful — and unnecessary.

Instead, just define a local macro whose value will either be ‘append’ or ‘replace,’ depending on whether the loop is in its first iteration or not, respectively:


foreach i of local iterations {
   if `i'==1 {
      local appendreplace "replace"
   }
   else {
      local appendreplace "append"
   }
   log using $logfile, `appendreplace'
   file open `myfile' using $somefilename, write `appendreplace'
   // ... and so on -- you're doing something big in this loop, right?
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *