Save command results to new frame in Stata

One of the new functions of Stata/MP 16 is the ability to use frames, i.e. keeping multiple data sets in memory. Unfortunately, not many existing commands fully optimize these new abilities.

For example, if you want to use the collapse command, which replaces the dataset with summary statistics, you cannot specify that the output should be in a new frame. You will to use 2-3 lines of code:

cap frame pwf
frame copy `=r(currentframe)' [newname], replace
frame [newname] : [stata_command]

To save time, the program framesave can automate this. The syntax is as follows:

framesave name_of_new_frame: stata_command

For example:

framesave summarystats: collapse (sum) employees (mean) wage, by(sector year)

Code:

cap program drop framesave
program define framesave

  * Saves the output of the command, e.g. collapse, to a frame

  gettoken left right2 : 0, parse(":")
  if `"`left'"' == ":" {
    local right `"`right2'"'
  }
  else {
   gettoken right3 right : right2, parse(":")
  }

  local 0 : copy local left

  syntax anything

  * Run the command on a copy of the current frame 
  cap frame pwf
  frame copy `=r(currentframe)' `anything', replace
  frame `anything' : `right'
end

Please note that if you want to use the new frame (e.g. browse of export), you still have to switch the active frame to the newly generated frame using the frame change command, or use the frame: prefix.