Initial commit

This commit is contained in:
2024-06-04 11:19:21 +02:00
commit a808b2a204
710 changed files with 277632 additions and 0 deletions

View File

@ -0,0 +1,417 @@
*! sasexe Version 2.2 dan.blanchette@duke.edu 04May2009
*! Center for Entrepreneurship and Innovation Duke University's Fuqua School of Business
* - added directory for SAS 9.2 executable
* - stopped having it use -shortdir- and started returning wsas in double quotes
* sasexe Version 2.1 dan.blanchette@duke.edu 16Mar2009
* - made it so saswrapper can run it
* sasexe Version 2.1 dan_blanchette@unc.edu 03Mar2008
* research computing, unc-ch
* - added a check for environment variable %MAINDIR% in foreach loop through users path
* if this variable doesn't exist then don't look for sas.exe there.
* - removed references to J: drive locations of SAS
* - added error message that -sasexe- cannot be run in Stata batch in Windows
* sasexe Version 2.0 dan_blanchette@unc.edu 06Sep2006
** the carolina population center, unc-ch
** - need to return what version of SAS is running
** - not only does sasexe look to see if sas executable file exists but also if it works
** and figures out what version it is.
** - looks in environment variable PATH as a last ditch effort to find the SAS executable file
** - added search for the char2fmt SAS macro file char2fmt.mac
** sasexe Version 1.0 dan_blanchette@unc.edu 02Sep2004
/* updated on 02Sep2004: added new drive specification for UNC afs pc-pkg space SAS users */
/* updated on 11Mar2004: added message to UNIX users on how to
* find their sas executable file. */
** sasexe Version 1.0 dan_blanchette@unc.edu 06Nov2003
program define sasexe, rclass
version 8
*** SET LOCATION OF SAS EXECUTABLE HERE ***
*------------------------------------------*
// set the macro var appropriate for your operating system
// and feel free to send me the location so that I can add it to the
// list of locations that -sasexe- searches through so that in future
// updates your executable location will already be set
local wsas `""' // location of windows sas executable file
local usas `""' // location of UNIX/Linux sas executable file
local rver `""' // version of sas you think you are running like v8, v9
// local rver `"v9"'
/* If you are using -savasas- and don't have SAS and just want to create a SAS program
* and temp data files set what version you think the SAS program will be run in here: */
local nosasver= `""' // this is not an option for -usesas-
*** SET LOCATION OF SAVASTATA MACRO HERE FOR USESAS ***
*-----------------------------------------------------*
/** for example:
local savastata "C:\ado\plus\s\savastata.sas" **/
local savastata ""
** note: if you set the location of savastata you must also set
* the locaton of char2fmt
*** SET LOCATION OF CHAR2FMT MACRO HERE FOR USESAS ***
*-----------------------------------------------------*
/** for example:
local char2fmt "C:\ado\plus\c\char2fmt.sas" **/
local char2fmt ""
** note: if you set the location of char2fmt you must also set
* the locaton of savastata
*****************************************************************
******* ! NO MORE EDITS SHOULD BE MADE AFTER THIS POINT ! *******
*****************************************************************
// the 2nd argument is the location of SAS executable if invoked by savas
if "`1'" == "savasas" & `"`2'"' != `""' & `"`2'"' != `"sascode"' {
local usas `"`2'"' // location of UNIX/Linux sas executable file
}
if `"`nosasver'"' == "" {
if "`c(os)'" == "Windows" & !missing(`"`usas'"') {
local usas = "" // set to missing for the logic of this program
}
else if "`c(os)'" != "Windows" & !missing(`"`wsas'"') {
local wsas = "" // set to missing for the logic of this program
}
** User set wsas or usas location so check it out **
** --------------------------------------------------------------------- **
if `"`wsas'"' != "" | "`usas'" != "" /* & "`2'" == "" */ { // sasexe tries to find sas executable otherwise
if "`c(os)'" == "Windows" {
if !missing(`"`wsas'"') {
capture confirm file `"`wsas'"'
if _rc==0 {
// find out if this works and what version
sasexe_ver, sasexe(`"`wsas'"')
if "`r(rver)'" == "" {
// if version wasn't figured out then sas didn't work
local wsas ""
}
else { // if rver is something then sas works
local rver "v`= int(`r(rver)')'"
di as res _n `"`1' has found the SAS executable file:"'
di as res `"`wsas'"'
}
}
}
}
else { // if os is not Windows (UNIX/Linux)
if !missing(`"`usas'"') {
capture confirm file `"`wsas'"'
if _rc==0 {
// find out if this works and what version
sasexe_ver, sasexe(`"`usas'"')
if "`r(rver)'" == "" {
// if version wasn't figured out then sas didn't work
local usas ""
}
else { // if rver is something then sas works
local rver "v`= int(`r(rver)')'"
di as res _n `"`1' has found the SAS executable file:"'
di as res `""`usas'""'
}
}
}
}
}
} // end of nosasver not set
** If above macros not set by user or set incorrectly **
** then have sasexe look in the usual locations **
** ---------------------------------------------------**
if "`1'"=="usesas" | "`1'"=="saswrapper" & (`"`savastata'"' == "" | `"`char2fmt'"' == "") {
foreach macro in savastata char2fmt {
capture confirm file `"x:\software/`macro'.sas"' /* network location */
if _rc==0 {
local `macro' `"x:\software/`macro'.sas"'
}
else {
// local set_macro `"/bigtemp/sas_macros/`macro'.sas"' /* CPC's location */
local set_macro `"/afs/isis/pkg/stata/.install/common/ado/updates/`macro'.sas"'
capture confirm file `"`set_macro'"' /* UNIX box location */
if _rc==0 {
local `macro' `"`set_macro'"'
}
else {
// find it in the adopath
capture findfile `macro'.sas
local cwd=`"`c(pwd)'"'
local dir=substr(`"`r(fn)'"',1,index(`"`r(fn)'"',"`macro'.sas")-1)
quietly cd `"`dir'"'
capture confirm file "`macro'.sas"
if _rc==0 {
local `macro' `"`c(pwd)'`c(dirsep)'`macro'.sas"'
}
quietly cd `"`cwd'"'
}
}
}
} /* end of if savastata or char2fmt not set */
// search even if sascode requested (`2' means sascode) since version (rver) can still be figured out
if `"`nosasver'"' == "" & (`"`wsas'"' == "" | `"`usas'"' == "" ) /* & "`2'" == "" */ { // sasexe tries to find sas executable otherwise
if "`c(os)'"=="Windows" & `"`wsas'"'=="" {
foreach sas in "c:\progra~1\sas\sasfou~1\9.2\sas.exe" /// 9.2
"C:\Program Files\SAS\SAS 9.2\SASFoundation\9.2\sas.exe" ///9.2
"d:\progra~1\sas\sasfou~1\9.2\sas.exe" /// 9.2
"C:\Program Files\SAS\SASFoundation\9.2(32-bit)\sas.exe" /// 9.2
"d:\Program Files\SAS\SASFoundation\9.2(32-bit)\sas.exe" /// 9.2
"d:\SAS\SASFoundation\9.2(32-bit)\sas.exe" /// 9.2
"d:\sasfou~1\9.2\sas.exe" /// 9.2
"Y:\SASSER~1\v9\sas\sas.exe" /// Win XP
"Y:\SAS_SE~1\V9\SAS\SAS.EXE" /// Win 2000
"c:\progra~1\sas\sas9~1.1\sas.exe" ///
"c:\progra~1\sas\sas9~2\sas.exe" ///
"c:\progra~1\sasins~1\sas\v9\sas.exe" ///
"d:\sasv9~1.1\sas\sas.exe" ///
"d:\sasv9~2\sas\sas.exe" ///
/// now try version 8
"c:\progra~1\sasins~1\sas\v8\sas.exe" ///
"d:\sasv8~1\sas\sas.exe" ///
"Y:\SAS_SE~1\V8\SAS\SAS.EXE" /// Win 2000
"Y:\SASSER~1\V8\SAS\SAS.EXE" /* Win XP */ {
capture confirm file "`sas'"
if _rc==0 { // success!
local wsas `"`sas'"' /* for Windows */
// find out if this works and what version
sasexe_ver, sasexe(`"`wsas'"')
if "`r(rver)'" == "" {
// if version wasn't figured out then sas didn't work
local wsas ""
}
else { // if rver is something then sas works
local rver "v`= int(`r(rver)')'"
di as res _n `"`1' is going to run SAS `rver' executable: "`wsas'" "'
continue, break // stop looking
}
}
} /* end of foreach loop */
} /* end of if Windows */
else if "`c(os)'"=="Unix" & "`usas'"=="" {
if "`c(machine_type)'" == "Sun Solaris" {
capture confirm file `"/opt/sas9.1/sas"'
if _rc==0 {
local usas "`usas'"
local rver `"v9"'
}
}
else if "`c(machine_type)'" == "PC" { /* for Linux work stations */
capture confirm file `"/usr/bin/sas"'
if _rc==0 {
local usas "/usr/bin/sas"
// let sasexe figure out what version of SAS
sasexe_ver, sasexe(`"`usas'"')
local rver "v`= int(`r(rver)')'"
}
else {
capture confirm file `"/afs/isis/pkg/sas/sas"'
if _rc==0 {
/* for Linux in pkg space */
local usas `"/afs/isis/pkg/sas/sas"'
local rver `"v9"'
}
}
} // end if "PC" / a Linux box
else if "`c(machine_type)'" == "IBM RS/6000" {
capture confirm file `"/afs/isis/pkg/sas/sas"'
if _rc==0 {
local usas `"/afs/isis/pkg/sas/sas"' /* for UNIX */
local rver `"v9"'
}
}
} /* end of if UNIX */
if `"`wsas'"'=="" & "`usas'"=="" { // if still not set
// look in user's path
local path : environment PATH
local delim ":"
if "`c(os)'" == "Windows" local delim ";"
// allows for dirs to have spaces in the directory names
foreach dir in "`: subinstr local path "`delim'" `"" ""', all'" {
if `= index(`"`dir'"',"%MAINDIR%")' & `"`: environment MAINDIR'"' == "" continue
if "`c(os)'" == "Windows" & `"`: dir "`dir'" files sas.exe'"' == `""sas""' {
capture confirm file `"`dir'\sas.exe"'
if _rc==0 {
local wsas `"`dir'\sas.exe"'
// find out if this works and what version
sasexe_ver, sasexe(`"`wsas'"')
if "`r(rver)'" == "" {
// if version wasn't figured out then sas didn't work
local wsas ""
}
else { // if rver is something then sas works
local rver "v`= int(`r(rver)')'"
di as res _n `"`1' is going to run SAS `rver' executable: "`wsas'" "'
continue, break // leave loop once found sas executable
}
}
} // end of if Windows
else if `"`: dir "`dir'" files sas'"' == `""sas""' {
capture confirm file `"`dir'/sas"'
if _rc==0 {
local usas `"`dir'/sas"'
sasexe_ver, sasexe(`"`usas'"')
if "`r(rver)'" == "" {
// if version wasn't figured out then sas didn't work
local usas ""
}
else { // if rver is something then sas works
local rver "v`= int(`r(rver)')'"
di as res _n `"`1' is going to run SAS `rver' executable: "`usas'" "'
continue, break // leave loop once found sas executable
}
}
}
} // end of foreach dir
if `"`wsas'"'=="" & "`usas'"=="" { // if _still_ not set
di "{error}Edit your sasexe.ado file to set the location *"
di "{error}of your SAS executable file. *"
which sasexe
di `" {stata adoedit sasexe:edit sasexe.ado} (click, to edit the sasexe.ado file, remember to save when done.)"'
if "`1'"=="savasas" di "{error}or use the {res}sascode {error}option in `1'. * "
if "`1'"=="usesas" di "{error} {help usesas:usesas} requires that you have a working version of SAS on this computer. "
if "`1'"=="saswrapper" di "{error} {help saswrapper:saswrapper} requires that you have a working version of SAS on this computer. "
if "`c(os)'"=="Unix" {
di `"{error} Your SAS executable is a file named "sas" not "sas.exe" and can be found by typing: *"'
di `"{text} which sas *"'
di `"{error} at a UNIX prompt. You may want to inform your UNIX administrator that *"'
di `"{error} you want to run SAS from Stata. * "'
}
exit 499
} // end of if wsas and usas _still_ empty
} // end of if wsas and usas still empty
} // end of if "`wsas'"=="" & "`usas'"=="" i.e. not set
/********* this block of code should not be needed anymore, it should not ever happen ****/
// check that if wsas or usas was set by user that they did it correctly
if `"`wsas'"'!="" & "`c(os)'"=="Windows" & "`2'"=="" { // `2' is if sascode requested
capture confirm file `"`wsas'"'
if _rc!=0 {
di `"{error}This is not the correct location of your SAS executable: "'
di `"{res}`wsas' "'
di "{error}Edit your sasexe.ado file to set the location of your sas.exe file. "
which sasexe
di `" {stata adoedit sasexe:edit sasexe.ado} (click, to edit the sasexe.ado file, remember to save when done.)"'
if "`1'"=="savasas" di "{error}or use the {res}sascode {error}option in `1'. "
exit 499
}
} /* end of if wsas not correctly set */
else if "`usas'"!="" & "`c(os)'"=="Unix" & "`2'"=="" { // `2' is if sascode requested
capture confirm file `"`usas'"'
if _rc!=0 {
di `"{error}This is not the correct location of your SAS executable: *"'
di `"{res}"`usas'" *"'
di "{error}Edit your sasexe.ado file to set the location *"
di "{error}of your sas executable file. *"
which sasexe
di `" {stata adoedit sasexe:edit sasexe.ado} (click, to edit the sasexe.ado file, remember to save when done.)"'
if "`1'"=="savasas" di "{error}or use the {res}sascode {error}option in `1'. *"
exit 499
}
} /* end of if usas not correctly set */
/****** (end) this block of code should not be needed anymore, it should not ever happen **/
if "`1'"=="usesas" | "`1'"=="saswrapper" {
foreach macro in savastata char2fmt {
capture confirm file `"``macro''"'
if _rc!=0 {
if `"``macro''"' != "" {
di `"{error}This is not the correct location of your `macro' macro: "'
di `"{res}``macro'' "'
}
else di `"{error}The file `macro'.sas was not found. {help `1':`1'} needs this file to run."'
di "{error}Edit your sasexe.ado file to set the location of your `macro'.sas file. "
which sasexe
di `" {stata adoedit sasexe:edit sasexe.ado} (click, to edit the sasexe.ado file, remember to save when done.)"'
exit 499
}
return local `macro' ``macro''
}
}
// if person knows they don't have sas and chooses what version to run, and is using
// the sascode option then replace rver with nosasver
if `"`nosasver'"' != "" & `"`2'"' != "" local rver=`"`nosasver'"'
// make sure v8.2 or v9.1.3 is not used as it's not necessary to be that exact
if index("`rver'","8") local rver = "v8"
else if index("`rver'","9") local rver = "v9"
else if index("`rver'","10") local rver = "v10"
else if index("`rver'","11") local rver = "v11"
else if index("`rver'","12") local rver = "v12"
if "`rver'" == "" & "`2'" == "" { // `2' is if sascode requested
di as error "`1' was unable to figure out what version of SAS you are running. *"
di as error "Please edit your {stata adoedit sasexe:sasexe.ado} file and specify the location of your SAS *"
di as error "executable file and the version of SAS you are running. *"
if "`usas'" != "" & "`c(os)'" != "Windows" {
di as res `"`1' found your SAS executable file here: "`usas'""'
}
else if `"`wsas'"' != "" & "`c(os)'" == "Windows" {
di as res `"`1' found your SAS executable file here: "`wsas'""'
}
exit 499
} // end of if rver still empty
else if "`rver'" == "" & "`2'" != "" { // `2' is if sascode requested
local rver "v9"
di as error _n `"{help savasas:savasas} is choosing to write code appropriate for SAS version 9. *"'
di as error `"If an alternate version of SAS is desired, please edit your {stata adoedit sasexe:sasexe.ado} file. *"'
}
return local rver "`rver'"
return local wsas `"`""`wsas'""'"'
return local usas `usas'
end
capture program drop sasexe_ver
program sasexe_ver, rclass
version 8
syntax, sasexe(string)
if "`c(os)'"=="Windows" & "`c(mode)'" == "batch" {
di as err "sasexe cannot be run in batch mode on Windows"
exit 499
}
tempfile sas_ver
quietly file open sasvfile using "`sas_ver'_version.sas", replace text write
file write sasvfile `"** program to figure out if SAS works and what version is running **;"' _n ///
`" data _null_; "' _n `" file "`sas_ver'_version.do";"' _n ///
`" put "capture program drop sas_rver"; "' _n ///
`" put "program sas_rver, rclass"; "' _n ///
`" put "return local rver ""&sysver."""; "' _n ///
`" put "end";"' _n ///
`" run; "'
file close sasvfile
capture confirm file `"`sas_ver'_version.sas"'
if _rc==0 {
local nologo = "-nologo"
// -nologo is not an option for UNIX/Linux SAS
if "`c(os)'"=="Unix" /* or Linux */ local nologo = ""
shell "`sasexe'" "`sas_ver'_version.sas" `nologo' -log "`sas_ver'_version.log"
capture confirm file `"`sas_ver'_version.do"'
if _rc==0 {
run `"`sas_ver'_version.do"'
sas_rver
return local rver "`r(rver)'"
}
capture erase `"`sas_ver'_version.sas"'
capture erase `"`sas_ver'_version.log"'
capture erase `"`sas_ver'_version.do"'
}
end

View File

@ -0,0 +1,751 @@
*! saswrapper Version 1.1 dan.blanchette@duke.edu 08Jul2009
*! Center for Entrepreneurship and Innovation Duke University's Fuqua School of Business
* -removed stray carriage return characters
* saswrapper Version 1.1 dan.blanchette@duke.edu 04May2009
* -made it fail more gracefully when usesas option specified and sas code had an error in it
* saswrapper Version 1.0 dan.blanchette@duke.edu 26Feb2009
program define saswrapper, rclass
version 8
syntax [varlist] [using/ ] [if] [in] [, PRE_sas_prog(string) POST_sas_prog(string) MEssy savasas(string) ///
usesas NODATA clear QUotes CHeck float char2lab NOFORMATS rename ]
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , start type(savas) message(`"saswrapper using `using', `messy' `savasas' `usesas' `nodata' `clear' `quotes' `check' `float' `char2lab' `noformats' `rename' "')
}
if "`c(os)'" == "Windows" & "`c(mode)'" == "batch" {
di as err "{help saswrapper:saswrapper} cannot be run in batch mode on Windows"
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(8) etime
}
exit 499
}
if `c(N)' == 0 & `"`savasas'"' != "" {
di as err "no data in memory to save to SAS" _n
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(8) etime
}
exit 499
}
if "`nodata'" != "" & `"`savasas'"' != "" {
di as err "cannot specify both nodata and savasas" _n
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(8) etime
}
exit 499
}
if `c(N)' == 0 & "`nodata'" == "" {
local nodata = "nodata"
}
if `"`usesas'"' != "" & `c(N)' != 0 & "`clear'" == "" {
di "{error} no, data in memory would be lost "
di "{error} use the {res}clear {error}option"
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(1) etime
}
exit 4
}
local formats = "formats"
if "`noformats'" != "" {
local formats = ""
}
* CAPTURE USER'S LOG
* ------------------
quietly log query
local usrlog `r(filename)'
* FIGURE OUT WHERE THE SAS EXECUTABLE IS
* --------------------------------------
sasexe saswrapper
local wsas `r(wsas)'
local usas `r(usas)'
local savastata `r(savastata)'
local char2fmt `r(char2fmt)'
local rver `r(rver)' // version of sas that's being run i.e. "v8", "v9" etc
local dirsep = "`c(dirsep)'"
if "`c(os)'" == "Windows" {
local dirsep = "\"
}
local dir = "`c(pwd)'`dirsep'"
if `"`using'"' != "" {
// see if there is even one double quote in using
local subtest : subinstr local using `"""' `""' , count(local cnt)
if `cnt' != 0 {
di `"{help saswrapper:saswrapper} {error}cannot handle directory or file names that contain double quotes. "'
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(2) etime
}
exit 499
}
/* if filename is given with directory info too,
* strip to just file name and to dir location */
if "`c(os)'" == "Windows" {
if index("`using'","/") {
local using : subinstr local using "/" "\" , all
}
}
if index("`using'","`dirsep'") {
local filen=substr("`using'",index("`using'","`dirsep'")+1,length("`using'"))
while index("`filen'","`dirsep'") !=0 {
local filen = substr("`filen'",index("`filen'","`dirsep'")+1,length("`filen'"))
}
local dir = substr("`using'",1,index("`using'","`filen'")-1)
}
else if index("`using'","\\\") == 1 { /* Universal naming convention */
local filen = substr("`using'",index("`using'","\\\")+2,length("`using'"))
while index("`filen'","\") !=0 {
local filen = substr("`filen'",index("`filen'","\")+1,length("`filen'"))
}
local dir = substr("`using'",1,index("`using'","`filen'")-1)
}
else { /* no directory given */
local filen = "`using'"
local dir = "`c(pwd)'`dirsep'"
}
/** extract file extension if there is one **/
if index("`filen'",".") {
local ext=substr("`filen'",index("`filen'","."),length("`filen'"))
while index("`ext'",".") > 0 {
local ext = substr("`ext'",index("`ext'",".")+1,length("`ext'"))
}
local ext = ".`ext'"
local filen = substr("`filen'",1,index("`filen'",".")-1)
}
if lower("`ext'") == "" { // guess that the user is wanting to use a .sas file
local using1 `"`using'.sas"'
local ext ".sas"
capture confirm file `"`using1'"'
if _rc == 0 {
capture confirm file `"`using'"'
if _rc == 0 {
di `"{error}The SAS file: "`using'" does exist, but so does the SAS file: "`using1'" '"'
di as text `"SAS will choose to run "`using1'" since it has the file extension ".sas" "'
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(3) etime
}
exit 601
}
}
// only here if this file does exist
local using `"`using'.sas"'
}
else if lower("`ext'") != ".sas" {
di as error `" "`ext'" is an invalid file extension "'
di as error `"{help saswrapper:saswrapper} can only run SAS program files which have the file extension ".sas" "'
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(3) etime
}
exit 601
}
capture confirm file `"`using'"'
if _rc != 0 {
di `"{error}The SAS file: `using' does not exist."'
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(3) etime
}
exit 601
}
} // end of if "using" != ""
local usasprog "`using'"
if "`usasprog'" == "" & `"`pre_sas_prog'"' == "" & `"`post_sas_prog'"' == "" {
di as err `"no SAS code to run "' _n
/* log usage of saswrapper */
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(3) etime
}
exit 601
}
/* set where temp directory is */
tmpdir
local tmpdir `"`r(tmpdir)'"'
local tfn = subinstr("`c(current_time)'",":","",.)
local sysjobid = substr("`tfn'",length("`tfn'")-5,length("`tfn'"))
local temp `"`macval(tmpdir)'_`sysjobid'"'
if "`nodata'" == "" {
if `"`savasas'"' == "" {
local stata_data `"`c(filename)'"'
if `: length local stata_data' != 0 {
capture _getfilename `"`stata_data'"' // get error message if only dir in using
local stata_data `"`r(filename)'"' // make using just the filename
local stata_data : subinstr local stata_data ".dta" "" // drop file extension
valid_dset_name, dset(`stata_data') `rename'
local stata_data = "`r(valid_dset_name)'"
}
else if `: length local stata_data' == 0 {
local stata_data = "stata_data"
}
}
else if `"`savasas'"' != "" {
valid_dset_name, dset(`savasas') `rename'
local stata_data = "`r(valid_dset_name)'"
}
if "`stata_data'" == "" local stata_data = "stata_data"
if "`check'" != "" {
di as result _n `"Compare results with SAS output that will be printed next "'
// no reason to set more off because if user quits no temp files have been written yet
local five_n = 5
if _N < 5 {
local five_n = _N
}
summarize `varlist' `if' `in'
describe `varlist'
list `varlist' in 1/`five_n'
}
di as result _n "now running {help savasas:savasas} to save the dataset `stata_data' to the SAS WORK library "
savasas `varlist' using "`temp'_statadata.sas7bdat" `if' `in' , `formats' `rename' `messy' ///
saswrapper saswrap_data(`stata_data') sysjobid(`sysjobid')
}
* WRITE SASWPAPPER SAS PROGRAM
* ----------------------------
saswrapper_sas , dirsep("`dirsep'") dir("`dir'") tmpdir("`tmpdir'") temp("`temp'") filen(`filen') sysjobid(`sysjobid') ///
usasprog("`usasprog'") pre_sas_prog(`" `pre_sas_prog' "') post_sas_prog(`" `post_sas_prog' "') ///
rver(`rver') savastata("`savastata'") `quotes' `check' `float' `char2lab' char2fmt("`char2fmt'") ///
stata_data(`stata_data') `usesas' `nodata'
* RUN SAS
* -------
if "`c(os)'" == "Unix" /* or Linux */ {
shell "`usas'" "`temp'_saswrapper.sas" -log "`temp'_saswrapper.log" -print "`temp'_saswrapper.lst"
} /* end of if Unix */
else if "`c(os)'" == "Windows" /* Windows */ {
shell `wsas' "`temp'_saswrapper.sas" -nologo -log "`temp'_saswrapper.log" -print "`temp'_saswrapper.lst"
} /* end of if Windows */
capture confirm file `"`temp'_sascoderr.sas7bdat"'
if _rc == 0 {
tempfile saswrapper_output
copy `"`temp'_saswrapper.txt"' `"`saswrapper_output'"', text
capture confirm file `"`saswrapper_output'"'
if _rc == 0 {
di as error _n "the submitted SAS code has an error in it " _n
}
// set usesas to missing so that saswrapper will fail gracefully
local usesas
}
* LOOK AT ANY REPORT FROM SAS
* ---------------------------
capture confirm file `"`temp'_report.log"'
if _rc == 0 {
type `"`temp'_report.log"'
if "`messy'" == "" {
erase `"`temp'_report.log"'
}
}
if "`usesas'" != "" {
* CLEAR DATA OUT OF MEMORY
* ------------------------
if "`clear'" != "" {
drop _all
label drop _all
}
* LOAD STATA DATASET INTO MEMORY
* ------------------------------
capture confirm file `"`temp'_infile.do"'
if _rc == 0 {
di as result _n "now loading the most recently created SAS dataset in submitted SAS program "
di as result " savastata SAS macro saved this dataset to Stata " _n
if `"`usrlog'"' != "" {
quietly log close
}
local cwd "`c(pwd)'"
** cd to where infile.do is **
quietly cd "`tmpdir'"
run `"_`sysjobid'_infile.do"'
if `"`usrlog'"' != "" {
quietly log using `"`usrlog'"' , append
}
* SET DATASET NAME
* ----------------
if index("$S_FN","`dirsep'") == 1 {
global S_FN : subinstr global S_FN "`dirsep'" ""
}
global S_FN `"`macval(dir)'$S_FN"'
// run savastata_report to see if SAS and Stata agree how many obs and vars there are
savastata_report
di " " _n // insert a blank space
** cd back to where you were **
quietly cd "`cwd'"
} /* if infile.do file exists */
else {
di `"{error}{help saswrapper:saswrapper} failed."'
capture confirm file `"`temp'_knerror.txt"'
if _rc == 0 {
// savastata failed with a known error so just let report.log show the error
if "`c(os)'" != "Windows" {
usesasdel `"`tmpdir'"' _`sysjobid'
}
if "`c(os)'" == "Windows" {
local usesasdeldir : subinstr local tmpdir `":"' `"\\\`= char(58)'"', all
usesasdel `"`usesasdeldir'"' _`sysjobid'
}
}
else {
di `"{error}If no error message above this one, then check out the SAS log file to see why. "'
di `" {view "`temp'_saswrapper.log"} "'
di `" and {view "`temp'_saswrapper.txt"} "'
di `"{inp}Erase these temporary files created by {help saswrapper:saswrapper} when done with them:"'
di `"{res}(files located in "`tmpdir'") "'
ls "`temp'_*"
if "`c(console)'" != "console" {
if "`c(os)'" != "Windows" {
di `"{res} {stata usesasdel `"`tmpdir'"' _`sysjobid':Click here to erase them all.} "'
}
if "`c(os)'" == "Windows" {
local usesasdeldir : subinstr local tmpdir `":"' `"\\\`= char(58)'"', all
di `"{res} {stata usesasdel `"`usesasdeldir'"' _`sysjobid':Click here to erase them all.} "'
}
}
}
if "`usasprog'" != "" {
di `""'
if "`c(console)'" != "console" {
di `"{inp}Click here to edit your SAS program and try it again. "'
di `" {stata `"doedit "`usasprog'""':`usasprog'} "'
}
else di `"Edit your SAS program: "`usasprog'" and try it again."' _n
}
capture which usagelog
if _rc == 0 {
usagelog , type(savas) uerror(6) etime
}
exit 499
}
} //end of if usesas
capture confirm file `"`temp'_saswrapper.txt"'
if _rc == 0 {
tempfile saswrapper_output
copy `"`temp'_saswrapper.txt"' `"`saswrapper_output'"', text
}
* CLEAN UP TEMP FILES
* -------------------
if "`messy'"=="" {
if "`c(os)'" != "Windows" {
usesasdel `"`tmpdir'"' _`sysjobid'
}
if "`c(os)'" == "Windows" {
local usesasdeldir : subinstr local tmpdir `":"' `"\\\`= char(58)'"', all
usesasdel `"`usesasdeldir'"' _`sysjobid'
}
} /* end of messy */
else {
di "{res}You have requested {help saswrapper:saswrapper} not to delete the intermediary files" ///
" created by {help saswrapper:saswrapper}:"
dir "`temp'_*"
di "{input}Files located here: "
di `"{input}"`tmpdir'" "'
if "`c(console)'" != "console" {
if "`c(os)'" != "Windows" {
di `"{res} {stata usesasdel `"`tmpdir'"' _`sysjobid':Click here to erase them all.} "'
}
if "`c(os)'" == "Windows" {
local usesasdeldir : subinstr local tmpdir `":"' `"\\\`= char(58)'"', all
di `"{res} {stata usesasdel `"`usesasdeldir'"' _`sysjobid':Click here to erase them all.} "'
}
}
} // of if else if messy
// this is 2nd to last since user may break -more- which cancels saswrapper
capture confirm file `"`saswrapper_output'"'
if _rc == 0 {
di as result "the following is the results of the SAS program: " _n
type `"`saswrapper_output'"'
}
// this is last since user may break -more- which cancels saswrapper
if "`usesas'" != "" {
if "`check'" != "" {
local gsfn : subinstr global S_FN ".dta" ""
display as res _n " Compare these results with the results provided by SAS "
display as res " in the file `gsfn'_SAScheck.lst. " _n
local five_n = 5
if _N < 5 {
local five_n = _N
}
summarize
describe
list in 1/`five_n'
di _n "You have requested to have savastata provide a check file:"
di `""`gsfn'_SAScheck.lst" "' _n
}
}
end /* end of saswrapper */
program define saswrapper_sas, nclass
syntax [, dirsep(string) dir(string) tmpdir(string) temp(string) filen(string) sysjobid(string) ///
usasprog(string) pre_sas_prog(string) post_sas_prog(string) ///
rver(string) savastata(string) quotes check float char2lab char2fmt(string) ///
stata_data(string) usesas NODATA]
version 8
quietly {
file open sasfile using `"`temp'_saswrapper.sas"', replace text write
file write sasfile `"* saswrapper SAS program *; "' _n _n ///
`" options nonotes nofmterr nocenter linesize=`c(linesize)' source2;"' _n _n ///
`" ** need to create this file now as may only be able to *"' _n ///
`" * erase it later. **; "' _n ///
`" libname _saswrap "`tmpdir'"; "'
file write sasfile `"* sas error test *; "' _n _n ///
`" data _saswrap._`sysjobid'_sascoderr; "' _n ///
`" do i = 1 to 1; "' _n ///
`" message="submitted SAS code has an error"; "' _n ///
`" end; "' _n ///
`" run; "' _n ///
`" %let syslast=; "' _n
if "`stata_data'" != "" { // put data (and formats catalog file) into WORK library
capture confirm file `"`temp'_statadata.sas7bdat"'
if _rc == 0 {
file write sasfile `" proc datasets library= _saswrap; "' _n ///
`" copy in= _saswrap out= work move; "' _n ///
`" select _`sysjobid'_statadata (memtype= data); "' _n ///
`" run; "' _n _n
file write sasfile `" proc datasets library= work; "' _n ///
`" change _`sysjobid'_statadata = `stata_data' / memtype= data; "' _n ///
`" run; "' _n ///
`" quit; "' _n _n ///
`" %let syslast=work.`stata_data'; "' _n _n
}
capture confirm file `"`temp'_statadata.sas7bcat"'
if _rc == 0 {
file write sasfile `" proc datasets library= _saswrap; "' _n ///
`" copy in= _saswrap out= work move; "' _n ///
`" select _`sysjobid'_statadata (memtype= catalog); "' _n ///
`" run; "' _n _n
file write sasfile `" proc datasets library= work; "' _n ///
`" change _`sysjobid'_statadata = formats / memtype= catalog; "' _n ///
`" run; "' _n ///
`" quit; "' _n _n
}
}
file write sasfile `" proc printto print="`temp'_saswrapper.txt" log="`temp'_saswrapper.txt"; "' _n ///
`" run; "' _n _n ///
`" options notes; "' _n _n
if "`check'" != "" & "`nodata'" == "" {
file write sasfile `" "' _n ///
`" /****** THE FOLLOWING IS THE DATA CHECK YOU REQUESTED ******/ "' _n
file write sasfile `" "' _n ///
`" proc means data=work.`stata_data'; "' _n ///
`" run; "' _n _n ///
`" proc contents data=work.`stata_data'; "' _n ///
`" run; "' _n _n ///
`" proc print data=work.`stata_data' (obs=5); "' _n ///
`" run; "' _n
file write sasfile `" "' _n ///
`" /************ END OF THE DATA CHECK YOU REQUESTED **********/ "' _n
}
if `"`pre_sas_prog'"' != " " { // two spaces because pre_sas_prog(`" `pre_sas_prog' "')
file write sasfile `" "' _n _n ///
`" /********* THE FOLLOWING IS YOUR pre_sas_prog CODE *********/ "' _n _n
local len_pre_sas_prog : length local pre_sas_prog
if `len_pre_sas_prog' < 256 { // 256 is the max but there is a space at beginning and end
file write sasfile `" `pre_sas_prog' "' _n _n
}
else {
tokenize `" `pre_sas_prog' "', parse(";")
local orig_length : length local pre_sas_prog
local nosemis : subinstr local pre_sas_prog ";" "", all
local s_length : length local nosemis
// tokenize puts the semicolons in the even numbered macro vars
local n_semis = (`orig_length' - `s_length' ) * 2
local odd = 1
forval line = 1/`n_semis' {
if `odd' == 3 {
local odd = 1
}
if `odd' == 1 { // tokenize puts the semicolons in the even numbered macro vars
file write sasfile `" ``line''; "' _n _n
}
local odd = `odd' + 1
}
}
// the following semi-colon is there in case user forgot to end their code with one.
file write sasfile `" ; "' _n _n ///
`" /************** END OF YOUR pre_sas_prog CODE **************/ "' _n _n
}
if "`usasprog'" != "" { /* user submitted a SAS program */
file write sasfile `" "' _n _n ///
`" /********* THE FOLLOWING IS YOUR SAS PROGRAM *********/ "' _n _n ///
`" %include"`usasprog'"; "' _n _n ///
`" /************** END OF YOUR SAS PROGRAM **************/ "' _n _n
}
if `"`post_sas_prog'"' != " " { // two spaces because pre_sas_prog(`" `post_sas_prog' "')
file write sasfile `" "' _n _n ///
`" /********* THE FOLLOWING IS YOUR post_sas_prog CODE *********/ "' _n _n
local len_post_sas_prog : length local post_sas_prog
if `len_post_sas_prog' < 256 { // 256 is the max but there is a space at beginning and end
file write sasfile `" `post_sas_prog' "' _n _n
}
else {
tokenize `" `post_sas_prog' "', parse(";")
local orig_length : length local post_sas_prog
local nosemis : subinstr local post_sas_prog ";" "", all
local s_length : length local nosemis
// tokenize puts the semicolons in the even numbered macro vars
local n_semis = (`orig_length' - `s_length' ) * 2
local odd = 1
forval line = 1/`n_semis' {
if `odd' == 3 {
local odd = 1
}
if `odd' == 1 { // tokenize puts the semicolons in the even numbered macro vars
file write sasfile `" ``line''; "' _n _n
}
local odd = `odd' + 1
}
}
file write sasfile `" "' _n _n ///
`" /************** END OF YOUR post_sas_prog CODE **************/ "' _n _n
}
// the following semi-colon is there in case user forgot to end their code with one.
file write sasfile `" ; proc printto; "' _n ///
`" run; "' _n ///
`" quit; ** close up anything they might have left going **; "' _n _n
if `"`usesas'"' != "" {
file write sasfile `" %let sortedby=; ** leave in for now **; "' _n _n ///
`"%macro makework; "' _n ///
`" run; "' _n ///
`" %let nobs=%sysfunc(getoption(obs)); "' _n ///
`" %if &syserr.^=0 or &nobs.=0 or "&syslast."="_NULL_" %then %do;"' _n ///
`" %goto nevrmind; "' _n ///
`" %end; "' _n ///
`" %let syslast1=&syslast.; "' _n _n
file write sasfile `" proc datasets library= _saswrap; "' _n ///
`" copy in= _saswrap out= work move; "' _n ///
`" select _`sysjobid'_sascoderr (memtype= data); "' _n ///
`" run; "' _n _n ///
`" quit; "' _n _n ///
`" %let syslast=&syslast1.; "' _n _n
file write sasfile `"%if "&syslast." ^= "_NULL_" %then %do; "' _n ///
`" %let ldset=%length(&syslast.); "' _n ///
`" %let decpos=%index(&syslast.,.); "' _n ///
`" %let llib=%substr(&syslast.,1,&decpos.-1); "' _n ///
`" %let dset=%substr(&syslast.,&decpos.+1,&ldset.-&decpos.); "' _n ///
`" %let dset=%sysfunc(lowcase(%nrbquote(&dset.))); "' _n _n
file write sasfile `" data _null_; "' _n ///
`" dsid=open("&syslast.",'i');"' _n `" sortedby=attrc(dsid,'SORTEDBY'); "' _n ///
`" call symput('sortedby',trim(sortedby));"' _n `" rc=close(dsid);"' _n `" run;"' _n _n
file write sasfile `" %if %index(%upcase(&sortedby.),DESCENDING) %then %do; "' _n ///
`" %* this is how Stata treats descending sortedby *; "' _n ///
`" %let sortedby= %substr(&sortedby.,1,%index(%upcase(&sortedby.),DESCENDING)-1); "' _n ///
`" %end;"' _n _n
file write sasfile `" ** if not in work make it be in work **; "' _n ///
`" %if %index(%upcase(&syslast.),WORK)^=1 %then %do; "' _n ///
`" data work.&dset.; "' _n ///
`" set &syslast.;"' _n `" run; "' _n ///
`" %end; ** end of if syslast is not in WORK **; "' _n _n ///
`" %end; ** end of if syslast is _NULL_ **; "' _n _n
file write sasfile `" %nevrmind: ; "' _n ///
`"%mend makework; "' _n ///
`"%makework; "'
if `c(stata_version)' < 9 & "`char2lab'" != "" {
noisily {
di as error `"option char2lab is not allowed prior to Stata 9."'
di as error `"option will be ignored."'
local char2lab ""
}
}
file write sasfile _n _n ///
`"%macro runit; "' _n _n ///
`" %let nobs=%sysfunc(getoption(obs)); "' _n ///
`" %if &syserr.^=0 or &nobs.=0 or "&syslast." = "_NULL_" %then %do;"' _n ///
`" proc printto log="`temp'_saswrapper.txt"; "' _n ///
`" run; "' _n ///
`" %put %upcase(error:) no dataset in SAS to load into Stata; "' _n ///
`" %goto nevrmind; "' _n ///
`" %end; "' _n
// need to put c(SE) and c(MP) in quotes since c(MP) doesn't exist in Stata 8
// need to pass a zero or a one to savastata for SE or MP
file write sasfile `" options nomprint nosource2; "' _n _n
file write sasfile `" %include "`savastata'"; "' _n ///
`" libname ___dir__ "`dir'" ; %* directory where _SAScheck.lst is saved to *; "' _n ///
`" %let _dir=%nrbquote(%sysfunc(pathname(___dir__))); "' _n ///
`" /* &sortedby. is global because of: call symput creates it */ "' _n ///
`" %savastata("`tmpdir'",`quotes' `char2lab' `check' messy `float',&sortedby., "' ///
`" `sysjobid',nosave,"&_dir.`dirsep'",`= ("`c(SE)'" == "1") + ("`c(MP)'" == "1")', "' ///
`" version=`c(stata_version)'); "' _n ///
`" %nevrmind: ; "' _n ///
`"%mend runit;"' _n `"%runit;"' _n
} // end of if usesas
file close sasfile
} /* end of quietly */
end
program valid_dset_name, rclass
syntax , dset(string) [rename]
version 8
local filen `dset'
local fc = substr("`filen'",1,1)
local swn = "0"
local hsc = "0"
if inlist("`fc'","0","1","2","3","4") | ///
inlist("`fc'","5","6","7","8","9") { // name starts with a number
local swn = "1"
}
if index("`filen'","~") | /// Has a bad character in name
index("`filen'","!") | ///
index("`filen'","@") | ///
index("`filen'","#") | ///
index("`filen'","$") | ///
index("`filen'","%") | ///
index("`filen'","^") | ///
index("`filen'","&") | ///
index("`filen'","*") | ///
index("`filen'","(") | ///
index("`filen'",")") | ///
index("`filen'","-") | ///
index("`filen'","+") | ///
index("`filen'","=") | ///
index("`filen'","[") | ///
index("`filen'","]") | ///
index("`filen'",":") | ///
index("`filen'",";") | ///
index("`filen'","'") | ///
index("`filen'","<") | ///
index("`filen'",">") | ///
index("`filen'","?") | ///
index("`filen'",",") | ///
index("`filen'","|") | ///
index("`filen'"," ") | ///
index("`filen'","{") | ///
index("`filen'","}") {
local hsc = "1"
}
if "`swn'" == "1" | "`hsc'" == "1" {
if "`rename'"=="" {
di `"{error}File name {res}"`filen'" {error}is not a valid SAS file name. *"'
if "`swn'" == "1" {
di `"{error}SAS file names cannot start with a number. *"'
}
if "`hsc'" == "1" {
di `"{error}SAS file names cannot contain special characters. *"'
}
}
if "`hsc'" == "1" {
// remove bad characters
foreach char in ~ ! @ # $ % ^ & * ( ) - + = [ ] : ; ' < > ? , | {
local filen = subinstr("`filen'","`char'","_",.)
}
local filen = subinstr("`filen'","{","_",.)
local filen = subinstr("`filen'","}","_",.)
local filen = subinstr("`filen'"," ","_",.)
if `"`: subinstr local filen "_" "" , all'"' == "" { // if nothing left, meaning, person used all bad characters
local filen= "okpopeye"
}
} // end of contains bad character
if "`swn'" == "1" { // name starts with a number
if length("`filen'") == 32 {
local filen = substr("`filen'",2,length("`filen'"))
local filen = "_`filen'"
}
else {
local filen ="_`filen'"
}
} // end of if started with number
if "`rename'" == "" {
di `"{error}The {res}rename {error}option will rename it for you to be: {res}"`filen'" "'
/* log usage of saswrapper */
capture which usagelog
if _rc==0 {
usagelog , type(savas) uerror(6) etime
}
exit 198
}
} /* if filen is not a valid SAS data file name */
return local valid_dset_name `filen'
end

View File

@ -0,0 +1,207 @@
{smcl}
{* version 1.0 26Feb2009}{...}
{hline}
help for {hi:saswrapper} {right:manual: {hi:[R] none}}
{right:dialog: {hi: none} }
{hline}
{title:Run a SAS program from within Stata}
{p 8 17 2}
{cmd:saswrapper}
[{varlist}]
{ifin}
[{cmd:using} {it:sas program filename}]
[{cmd:,}
{cmdab:pre:_sas_prog(`"}{it:sas code}{cmd:"')}
{cmdab:post:_sas_prog(`"}{it:sas code}{cmd:"')}
{cmdab:ch:eck}
{cmdab:me:ssy}
{cmd:usesas}
{cmd:nodata}
{cmd:savasas(}{it:sas dataset name}{cmd:)}
{cmd:noformats}
{cmd:rename}
{cmd:clear}
{cmd:char2lab}
{cmd:float}
{cmdab:qu:otes}]{p_end}
{title:Description}
{p 4 4 2}{cmd:saswrapper} runs a SAS program in batch and prints the output in the Stata results window/log file.
This usually occurs by specifying a SAS program file after {cmd:using}, but {cmd:saswrapper} can also run
SAS code specified by the {cmd:pre_sas_prog()} and/or {cmd:post_sas_prog()} options. By default, {cmd:saswrapper}
will save the current data in memory using {help savasas:savasas} and make it available in SAS's WORK library. If
that is not desired, use the {cmd:nodata} option. The {cmd:usesas} option tells {cmd:saswrapper} to load the
last SAS dataset created in the WORK library by the submitted SAS program into Stata using the {cmd:SAVASTATA} SAS macro.{p_end}
{p 4 4 2}{cmd:NOTE: saswrapper} calls SAS to run the SAS program. This requires the ability to run SAS on your computer.
If {cmd:saswrapper} does not run SAS for you, your {cmd:sasexe.ado} file may need to be edited to set the location of your
SAS executable file ({cmd:sas.exe}) and your {cmd:SAVASTATA} SAS macro file ({cmd:savastata.sas}).
It may be that {cmd:saswrapper} will be able to run with the default settings in {cmd:sasexe.ado}. See the
{help saswrapper##setup:setup instructions} below.{p_end}
{p 4 4 2}{cmd:saswrapper} uses the {cmd:SAVASTATA} SAS macro to create the Stata dataset from the SAS dataset when the
{cmd:usesas} option is specified. {cmd:saswrapper} downloads the {cmd:SAVASTATA} SAS macro and stores it where
user-written Stata ado-files are stored that begin with the letter "s". This macro can be used in SAS.
Learn about {cmd:SAVASTATA} here:
{browse "http://faculty.fuqua.duke.edu/~blanc004/sas_to_stata/savastata.html":http://faculty.fuqua.duke.edu/~blanc004/sas_to_stata/savastata.html }{p_end}
{title:Options}
{p 4 8 2}{cmd:using} {it:sas program filename} specifies {cmd:saswrapper} to run this SAS program. {cmd:saswrapper}
assumes the SAS program file extension {cmd:.sas} if no file extension/suffix is specified.{p_end}
{p 4 8 2}{cmd:pre_sas_prog()} and/or {cmd:post_sas_prog()} contain SAS code to be run by {cmd:saswrapper}. If SAS
programming code is supplied by {cmd:using}, {cmd:pre_sas_prog()}, and {cmd:post_sas_prog()} then the order the
code will be run is:{p_end}
{p 14 18 2}{cmd:pre_sas_prog()}{p_end}
{p 14 18 2}{cmd:using}{p_end}
{p 14 18 2}{cmd:post_sas_prog()}{p_end}
{p 8 8 2}It is best to enclose the SAS code within compound double quotes:{p_end}
{p 8 8 2}{cmd:. saswrapper, pre_sas_prog(`"proc means;"') }{p_end}
{p 8 8 2} in case the SAS code contains any double quotes. An interesting way to submit SAS code is
to first put it in a {help local:local} macro and use three forward slashes to continue the line:{p_end}
{p 8 8 2}{cmd:. local pre_sas_prog data new; /// }{p_end}
{p 8 8 2}{cmd: set work.stata_data; /// }{p_end}
{p 8 8 2}{cmd: gender = "female"; /// }{p_end}
{p 8 8 2}{cmd: run; }{p_end}
{p 8 8 2}{cmd:. saswrapper , pre_sas_prog(`" `pre_sas_prog' "')}{p_end}
{p 8 8 2}You can put a lot of SAS code in a {help local:local} macro if you don't use an equal sign ({cmd:=})
after then local macro name. For the above example to work, Stata has to be using the carriage
return as an end-of-line delimiter and not semi-colons which is changed by the {help #delimit:#delimit}
command. Stata will see Stata-style {help comments:comments} in the SAS code as Stata comments so
avoid starting a line with a star/asterisk "*":{p_end}
{p 8 8 2}{cmd: * some comment ; /// }{p_end}
{p 8 8 2} because Stata will comment out the three forward slashes at the end and thus end the input to the
local macro. Since the contents of the local macro will be one long line, do not attempt to do anything
in your SAS code that expects carriage returns like the SAS datalines statement that reads in raw data.{p_end}
{p 4 8 2}{cmd:check} specifies to generate basic stats for both the SAS and Stata datasets for the user
to make sure {cmd:saswrapper} created the files correctly. This is a comparison that should be done after
any datafile is converted to any other type of datafile by any software. The SAS file is created in the
same directory as the SAS program specified in {cmd:using} or if no program was specified in {cmd:using}
then it will be created in the current directory. The file is named starting with the name of the datafile
followed by "_SAScheck.lst" (SAS). e.g. "mySASdata_SAScheck.lst"{p_end}
{p 4 8 2}{cmd:messy} specifies that all the intermediary files created by {cmd:saswrapper} during its operation
are not to be deleted. The {cmd:messy} option prevents {cmd:saswrapper} from cleaning up after it has
finished. This option is mostly useful for debugging purposes in order to find out where something went
wrong. All intermediary files have a name starting with an underscore "_" followed by the process ID and
are located in Stata's temp directory.{p_end}
{p 4 8 2}{cmd:usesas} specifies to load the SAS dataset into memory that was most recently created in the
SAS WORK library in the SAS program submitted to {cmd:saswrapper}. {cmd:saswrapper} figures out how much
memory the SAS dataset will require to be loaded into Stata and sets Stata's memory for you if your memory
setting is less than is required.{p_end}
{p 4 8 2}{cmd:nodata} specifies to override the default behavior of {cmd:saswrapper} which is to save the
current dataset in memory to the SAS WORK library. Use this option when your SAS program is not going to
use the dataset in memory.{p_end}
{p 4 8 2}{cmd:savasas} specifies a different dataset name than the name of the dataset in memory.
If the dataset in memory does not have a name and the option {cmd:savasas} is not used, then the
dataset in memory will be available in SAS's WORK library as "stata_data" (a.k.a. "WORK.STATA_DATA").{p_end}
{title:Options when saving data to SAS}
{p 4 8 2}{cmd:varlist} specifies what selection of variables in the dataset in memory are to be saved
to the SAS dataset in the WORK library in the SAS program submitted to {cmd:saswrapper}. If no variables
are specified then all variables will be saved the SAS dataset.{p_end}
{p 4 8 2}{cmd:if} {it:exp} subsets the dataset in memory before saving the dataset to the SAS dataset in
the WORK library in the SAS program submitted to {cmd:saswrapper}.{p_end}
{p 4 8 2}{cmd:in} {it:range} subsets the dataset in memory before saving the dataset to the SAS dataset in
the WORK library in the SAS program submitted to {cmd:saswrapper}.{p_end}
{p 4 8 2}{cmd:noformats} specifies that no value labels be saved as SAS formats.{p_end}
{p 4 8 2}{cmd:rename} specifies that any required renaming of file name and/or variable names is
to be done when saving the dataset in memory to SAS using {help savasas:savasas}. The {cmd:rename}
option is only necessary when variable names are not unique in SAS. {cmd:savasas} displays the list
of renamed variables. {cmd:rename} also renames the SAS file name when the name provided is not a
valid SAS file name.{p_end}
{title:Options when using the usesas option}
{p 4 8 2}{cmd:clear} specifies to clear the data currently in memory before running {cmd:saswrapper}.{p_end}
{p 4 8 2}{cmd:char2lab} specifies to encode long SAS character variables like the Stata
command {help encode:encode}. Character variables that are too long for a Stata string
variable are maintained in value labels.{p_end}
{p 4 8 2}{cmd:float} specifies that numeric variables that would otherwise be stored as numeric type
double be stored with numeric type float. This option should only be used if you are certain you
have no integer variables that have more than 7 digits (like an id variable).{p_end}
{p 4 8 2}{cmd:quotes} specifies that double quotes that exist in string variables are to be replaced
with single quotes. Since the data are written out to an ASCII file and then read into Stata,
there are rare instances when double quotes are not allowed inside string variables.{p_end}
{title:Examples}
{p 4 8 2}{cmd:. saswrapper using "mySASprog.sas" }{p_end}
{p 4 8 2}{cmd:. saswrapper using "mySASprog.sas", nodata usesas clear }{p_end}
{p 4 8 2}{cmd:. saswrapper using "c:\data\mySASprog.sas", savasas(tester) check }{p_end}
{p 4 8 2}{cmd:. saswrapper , pre_sas_prog(`" proc print; "')}{p_end}
{p 4 8 2}{cmd:. saswrapper , pre(`" data new; set work.stata_data; if income > 0 then do; employed = 1; output; end; run; "') usesas clear}{p_end}
{p 4 8 2}{cmd:. saswrapper , post(`" proc univariate; "')}{p_end}
{p 4 8 2}{cmd:NOTE:} If you are setting up this program on your computer for
the first time, please edit sasexe.ado to set the location of your SAS
executable file (sas.exe). If you do not, {cmd:saswrapper} will try to set it
for you. The sasexe.ado file is an ASCII text file and should
be saved as such after editing. Stata's {cmd:do-file} editor will do the trick.{p_end}
{marker setup}
{title:Setting up saswrapper}
{p 4 4 2}
If you are setting up this program on your computer for the first time, you may need to edit the {cmd:sasexe.ado} file to
set the location of your SAS executable file ({cmd:sas.exe}). If you do not, {cmd:saswrapper} will look in the "usual"
locations for it. {cmd:saswrapper} also may need to have the location of the SAS macro {cmd:savastata.sas} set. The
{cmd:sasexe.ado} file is an ASCII text file and should be saved as such after editing. Stata's do-file editor will do
the job. {stata quietly adoedit sasexe:edit sasexe.ado} (click, to edit the {cmd:sasexe.ado} file, remember to save when
done.){p_end}
{title:Author}
{p 4 4 2}
Dan Blanchette {break}
Center of Entrepreneurship and Innovation {break}
Duke University's Fuqua School of Business {break}
Dan.Blanchette@Duke.edu{p_end}
{title:Also see}
{p 4 13 2}On-line: {help savasas:savasas}, {help usesas:usesas}{p_end}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,308 @@
{smcl}
{* version 2.1 12Mar2009}{...}
{* 09Jul2005 - updated assuming SAS 9 is current version of SAS}{...}
{* 02Dec2004 - improved smcl code}{...}
{* 19Oct2004 - minor edits}{...}
{* 05Nov2003}{...}
{hline}
help for {hi:savasas} {right:manual: {hi:[R] none}}
{right:dialog: {hi: none} }
{hline}
{title:Save dataset as a SAS dataset}
{p 8 17 2}{cmd:savasas}
[{it:varlist}]
[{cmd:using} {it:filename}]
{ifin}
[{cmd:,} {cmdab:t:ype(}{it:version_of_sas_data_file}{cmd:)}
{cmd:replace}
{cmdab:for:mats}
{cmdab:ren:ame}
{cmdab:me:ssy}
{cmdab:ch:eck}
{cmd:sascode}
]{p_end}
{title:Description}
{p 4 4 2}{cmd:NOTE:} Before the first use of {cmd:savasas} the {cmd:sasexe.ado}
file may need to be edited to set the location of your SAS executable file. Instructions on how
to do this is at the bottom of this help file.{p_end}
{p 4 4 2}{cmd:savasas} saves the Stata dataset in memory as a SAS file. By default the output dataset
will have the same name and be in the same directory, but with the ".sas7bdat" file name extension
and contain all observations and every variable in the Stata datafile.
{cmd:savasas} can save to other versions of SAS:
Version 8 or 9 (*.sas7bdat), Version 6 (*.sd2/*.ssd01/*.ssd02), SAS 6 Transport/xport (*.xpt).{p_end}
{p 8 8 2}The procedure is as follows:{p_end}
{p 8 8 2}(1) {cmd:savasas} uses {help fdasave:fdasave} to save the dataset in memory temporarily to a
SAS xport datafile.{p_end}
{p 8 8 2}(2) {cmd:savasas} writes a SAS input program to load the data into SAS and to assign variable
names, labels (and formats).{p_end}
{p 8 8 2}(3) {cmd:savasas} runs the program in SAS in batch mode to load the xport datafile created by
{help fdasave:fdasave}.{p_end}
{p 12 12 2 }Note to Windows users: This is where the Windows operating system will pop-up windows
that indicate that SAS is running in batch. Do not try to close these windows as that will
potentially halt {cmd:savasas}.{p_end}
{p 8 8 2}(4) SAS saves the data as whatever version SAS file type was specified.{p_end}
{p 4 4 2}For Stata SE users: the maximum length for a string variable is 244 characters.
In such cases, the first 200 characters will be taken and passed on to SAS (this is a limitation of
the SAS xport dataset used to transfer data from Stata to SAS).{p_end}
{p 4 4 2}{cmd:NOTE: savasas} calls SAS to run the SAS program. This requires the ability to
run SAS on your computer. If you do not have a working copy of SAS, use the {cmd:sascode}
option and copy the SAS program ({it:myData}_infile.sas) and the SAS xport datafile
({it:myData}.xpt) to a machine that has a working copy of SAS. The SAS program will
need to be modified to point to the location of the SAS xport datafile.{p_end}
{p 4 4 2}When {cmd:savasas} has successfully saved your data as a SAS dataset it will display
a message similar to the following:{p_end}
{p 4}{cmd:savasas} successfully saved the SAS file: *{p_end}
{p 4}c:\myData\MySASdata.sas7bdat *{p_end}
{p 4}SAS reports that the dataset has 1000 observations and 20 variables. *{p_end}
{title:Options}
{p 4 8 2}{cmd:type(}{it:version_of_sas_data_file}{cmd:)} specifies the SAS datafile version
desired, from the following list:
{p 8 8 2}{ul:one of} {space 5}{ul:SAS version datafile}{p_end}
{p 12 8 2}{cmd:sas}{space 9}current version of SAS * {it:the default if no type specified} *{p_end}
{p 12 8 2}{cmd:sas6}{space 8}SAS version 6{p_end}
{p 12 8 2}{cmd:sasx}{space 8}SAS version 6 transport/xport{p_end}
{p 8 8 2}Hint: If you specify the correct file name extension, you do not have to specify {cmd:type}.
Remember that a current version SAS (.sas7bdat) file will be created if no file extension or type specification
is made.{p_end}
{p 8 8 2}SAS version 6 and Transport/xport file restrictions:{p_end}
{p 12 12 2} 1) File names or variable names cannot be longer than 8 characters.
{cmd:savasas} checks for names that are longer than 8 characters;
and, if the {cmd:rename} option is issued, renames them to the first 8 characters or up to 7 plus a number.
In addition, it displays the list of renamed variables.{p_end}
{p 12 12 2} 2) Variable labels can be a maximum of 40 characters. {cmd:savasas} saves the first 40
characters.{p_end}
{p 4 8 2}{cmd:replace} works like Stata's replace in that it allows you to overwrite the SAS data
file if it already exists.{p_end}
{p 4 8 2}{cmd:formats} specifies that value labels are to be saved as SAS formats in a file that will
have the same name as the datafile but with the ".sas7bcat" file extension. This formats catalog
file will be created in the same directory as the SAS datafile. To use this SAS formats catalog
file you will need to add code to your program to make SAS aware that this file contains format
definitions used by variables in the dataset. Your code should look something like this:{p_end}
{p 8 8 2}libname in "c:\myData";{p_end}
{p 8 8 2}options fmtsearch=(in.mySASdataset);{p_end}
{p 8 8 2} NOTE: SAS user-defined formats for versions prior to SAS version 9 have to be 8 characters or less and cannot end in a number.
This is a list of format names that SAS reserves and thus cannot be user-defined format names:{p_end}
{p 8 8 2}
{cmd:best},
{cmd:binary},
{cmd:comma},
{cmd:commax},
{cmd:d},
{cmd:date},
{cmd:datetime},
{cmd:dateampm},
{cmd:day},
{cmd:ddmmyy},
{cmd:dollar},
{cmd:dollarx},
{cmd:downame},
{cmd:e},
{cmd:eurdfdd},
{cmd:eurdfde},
{cmd:eurdfdn},
{cmd:eurdfdt},
{cmd:eurdfdwn},
{cmd:eurdfmn},
{cmd:eurdfmy},
{cmd:eurdfwdx},
{cmd:eurdfwkx},
{cmd:f},
{cmd:float},
{cmd:fract},
{cmd:hex},
{cmd:hhmm},
{cmd:hour},
{cmd:ib},
{cmd:ibr},
{cmd:ieee},
{cmd:julday},
{cmd:julian},
{cmd:percent},
{cmd:minguo},
{cmd:mmddyy},
{cmd:mmss},
{cmd:mmyy},
{cmd:monname},
{cmd:month},
{cmd:monyy},
{cmd:negparen},
{cmd:nengo},
{cmd:numx},
{cmd:octal},
{cmd:pd},
{cmd:pdjulg},
{cmd:pdjuli},
{cmd:pib},
{cmd:pibr},
{cmd:pk},
{cmd:pvalue},
{cmd:qtr},
{cmd:qtrr},
{cmd:rb},
{cmd:roman},
{cmd:s370ff},
{cmd:s370fib},
{cmd:s370fibu},
{cmd:s370fpd},
{cmd:s370fpdu},
{cmd:s370fpib},
{cmd:s370frb},
{cmd:s370fzd},
{cmd:s370fzdl},
{cmd:s370fzds},
{cmd:s370fzdt},
{cmd:s370fzdu},
{cmd:ssn},
{cmd:time},
{cmd:timeampm},
{cmd:tod},
{cmd:weekdate},
{cmd:weekdatx},
{cmd:weekday},
{cmd:worddate},
{cmd:worddatx},
{cmd:wordf},
{cmd:words},
{cmd:year},
{cmd:yen},
{cmd:yymm},
{cmd:yymmdd},
{cmd:yymon},
{cmd:yyq},
{cmd:yyqr},
{cmd:z},
{cmd:zd}{p_end}
{p 4 8 2}{cmd:savasas} will make some attempt to rename invalid SAS formats but it would be best for
you to rename or drop them yourself before saving to SAS. Formats will be renamed if needed.{p_end}
{p 4 8 2}{cmd: rename} specifies that any required renaming of file name and/or variable names is
to be done. The {cmd:rename} option is only necessary when saving to SAS 6/transport or when
variable names are not unique in SAS. When saving to SAS 6/transport {cmd:rename} attempts to rename
long variable names (more than 8 characters) to be unique by shortening all long variable names to the
first 8 characters or up to the 7 plus a number. {cmd:savasas} displays the list of renamed variables.
{cmd:rename} also renames the SAS file name when the name provided is not a valid SAS file name.{p_end}
{p 4 8 2}{cmd:messy} specifies that all the intermediary files created by {cmd:savasas} during
its operation are not to be deleted. The {cmd:messy} option prevents {cmd:savasas} from
cleaning up after it has finished. This option is mostly useful for debugging purposes in
order to find out where something went wrong. All intermediary files have a name starting
with an underscore (_) followed by the process ID and are located in Stata's temp directory.{p_end}
{p 4 8 2}{cmd:check} specifies that basic stats for both datasets are to be generated to compare
the Stata input dataset with the SAS output dataset in order to make sure {cmd:savasas}
created the files correctly. This is a comparison that should be done after any datafile
is converted to any other type of datafile by any software. The SAS file is created in the
same directory as the output SAS datafile and is named starting with the name of the data
file followed by "_SAScheck.lst" (SAS), for example: "{it:mydata}_SAScheck.lst"{p_end}
{p 4 8 2}{cmd:sascode} specifies that only a SAS xport datafile and an input SAS program are
to be created. By default, {cmd:savasas} executes all four steps outlined above. The
{cmd:sascode} option aborts this process after step (2). The user then needs to read in
the data {it:manually} using SAS. For example: {cmd:savasas} writes a SAS program {it:myData}_infile.sas
to read in the xport datafile {it:myData}.xpt.{p_end}
{title:Examples}
{p 4 4 2}To save the dataset in memory to the same directory with the same name as the dataset in memory
as a sas7bdat file, type{p_end}
{p 4 8 2}{cmd:. savasas }{p_end}
{p 4 4 2}To save the dataset in memory to the current directory with the name mySASdata as a sas7bdat file, type{p_end}
{p 4 8 2}{cmd:. savasas using mySASdata}{p_end}
{p 4 4 2}To save the dataset in memory to c:\data\ directory with the name mySASdata as a sas7bdat file
and create 2 check files, type{p_end}
{p 4 8 2}{cmd:. savasas using c:\data\mySASdata.sas7bdat, check}{p_end}
{p 4 4 2}To save only variables between var1 and var20 from the dataset in memory to the current directory
with the name mySASdata as a sas7bdat file and create a formats.sas7bcat file containing SAS formats
of any Stata value labels, replacing an existing file if necessary, type{p_end}
{p 4 8 2}{cmd:. savasas gender-q32_b using mySASdata, formats replace}{p_end}
{p 4 4 2}More examples:{p_end}
{p 4 8 2}{cmd:. savasas using mySASdata.sas7bdat, replace }{p_end}
{p 4 8 2}{cmd:. savasas in 1/30 using mySASdata, type(sas6) check}{p_end}
{p 4 8 2}{cmd:. savasas using mySASdata, sascode type(sas6)}{p_end}
{p 4 8 2}{cmd:. savasas using mySASdata, messy type(sasx) rename}{p_end}
{title:Setting up savasas}
{p 4 4 2}If you are setting up this program on your computer for
the first time, please edit {cmd:sasexe.ado} to set the location of your SAS
executable file (sas.exe). If you do not, {cmd:savasas} will look in the "usual" locations for it.
The {cmd:sasexe.ado} file is an ASCII text file and should
be saved as such after editing. Stata's {cmd:do-file} editor will do the trick.{p_end}
{p 4 4 2}{stata quietly adoedit sasexe:edit sasexe.ado} (click, to edit the {cmd:sasexe.ado} file, remember
to save when done.){p_end}
{title:Author}
{p 4 4 2}
Dan Blanchette {break}
Center of Entrepreneurship and Innovation {break}
Duke University's Fuqua School of Business {break}
Dan.Blanchette@Duke.edu{p_end}
{title:Acknowledgements}
{p 4 4 2}
The user-written program {cmd:outdat} inspired this program.{p_end}
{title:Also see}
{p 4 13 2}On-line: {help fdasave}, {help save},
{help outdat} (if installed),
{help usesas} (if installed){p_end}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,75 @@
*! sdpair.ado 1.00 by PTS (p.seed@umds.ac.uk) (STB-55: sbe33)
*! Based on Pitman (1939) Biometrika 31: 9
*! as in Snedecor & Cochran (1967) "Statistical methods (6th ed)" (Iowas State UP)
prog define sdpair
version 5.0
local varlist " req ex min(2) max(2)"
local if "opt"
local in "opt"
local weight "fweight aweight"
local options "format(string) Level(real 100)"
parse "`*'"
tempvar touse sum diff
mark `touse' `if' `in'
markout `touse' `varlist'
if "`format'" == "" { local format "%6.4f" }
if `level' == 100 { local level = $S_level }
if `level' > 1 { local level = `level' /100 }
parse "`varlist'", parse(" ")
qui summ `1' if `touse' [`weight'`exp']
tempname var1 n df var2 F r t p K lcb ucb
scalar `var1' = _result(4)
scalar `n' = _result(2)
scalar `df' = `n' - 2
qui summ `2' if `touse' [`weight'`exp']
scalar `var2' = _result(4)
scalar `F' = `var1'/`var2'
qui corr `varlist' if `touse' [`weight'`exp']
scalar `r' = _result(4)
scalar `t' = ((`F'-1)/2)*( (`df')/ ((1-`r'*`r')*`F') )^.5
* Note: under the null hypothesis, phi = 1
* di "t = |" `t' "|"
scalar `p' = tprob(`df', `t')
scalar `K' = 1 + 2*(1-`r'*`r')*invt(`df', `level')^2/(`df')
scalar `lcb' = `F' * (`K' - (`K'*`K'-1)^.5)
scalar `ucb' = `F' * (`K' + (`K'*`K'-1)^.5)
local label1 : variable label `1'
if "`label1'" == "" {local label1 `1' }
local label2 : variable label `2'
if "`label2'" == "" {local label2 `2' }
zap_s
global S_1 = `n'
global S_2 = `t'
global S_3 = `df'
global S_4 = `p'
global S_5 = `F'^.5
global S_6 = `lcb'^.5
global S_7 = `ucb'^.5
di in gr _n(2) "Pitman's variance ratio test between `label1' and `label2': "
di in gr _n "Ratio of Standard deviations = " in ye `format' `F'^.5, "
di in gr 100*`level' "% Confidence Interval " in ye `format' `lcb'^.5 in gr " to " in ye `format' `ucb'^.5
di in gr "t = " in ye %6.3f `t' in gr ", df = " in ye `df' in gr ", p = " in ye %6.3f `p'
end vartest

View File

@ -0,0 +1,48 @@
.-
help for ^sdpair^ (STB-55: sbe33)
.-
Pitman's test of difference in variance for paired data
-------------------------------------------------------
^sdpair^ varname1 varname2 [weight] [^if^ exp] [^in^ range]
[^, format(^str^) l^evel^(^#^)^ ]
^fweight^s and ^aweight^s are allowed; see help @weights@.
Description
-----------
^sdpair^ produces Pitman's confidence interval for the ratio of variances
for paired data.
Options
-------
^format(^str^)^ sets the format for the display of results.
^level(^#^)^ specifies the confidence level, in percent, for confidence
intervals. The default is ^level(95)^ or as set by ^set level^.
Examples
--------
. ^use suv2^
. ^sdpair log_p log_gp^
Author
------
Paul Seed
GKT School of Medicine
King's London, UK
email: paul.seed@@kcl.ac.uk
Also see
--------
STB: STB-55 sbe33

View File

@ -0,0 +1,452 @@
*! seeout version 1.2.3 21oct2009 by roywada@hotmail.com
*! (to accompany -outreg2-)
program define seeout
version 7.0
syntax [using] [,LABel LABelA(passthru) ]
if `"`using'"'~="" {
*** clean up file name, attach .txt if no file type is specified
local rest "`using'"
* strip off "using"
gettoken part rest: rest, parse(" ")
* strip off quotes
gettoken first second: rest, parse(" ")
cap local rest: list clean local(rest)
local rabbit `"""'
if index(`"`using'"', ".")==0 {
local file = `"`rabbit'`first'.txt`rabbit'"'
local using = `"using `file'"'
}
else {
local file = `"`rabbit'`first'`rabbit'"'
local using = `"using `file'"'
}
*** seeout the output
*local cl `"{stata `"seeout `pref'"': seeout `pref'}"'
*di as txt `"`cl'"'
seeing `using', `label'
}
else {
*** read the set preference if not out of date
* NOTE: `0' is written over below
cap quietly findfile outreg2.pref
tempname myfile
cap file open `myfile' using `"`r(fn)'"', read text
cap file read `myfile' date
cap file read `myfile' pref
cap file read `myfile' options
cap file close `myfile'
if "`date'"== "`c(current_date)'" {
*** seeout the output
if index(`"`options'"', "label")~=1 & index(`"`options'"', `"label("')==0 {
tokenize `"`options'"'
local count: word count `options'
if `count'~=0 {
local test 0
forval num=1/`count' {
if `"``num''"'=="label" {
local label label
}
}
}
}
} /* ? */
gettoken first file: pref
*** codes recycled from outreg2:
* strip off quotes and extension
gettoken first second: file, parse(" ")
local temp = `"`first'"'
local next_dot = index(`"`temp'"',".")
local next_strip = substr(`"`temp'"',1,`=`next_dot'-1')
local strippedname = substr(`"`temp'"',1,`=`next_dot'-1')
* check for more dots
local change 0
while `change'==0 {
local temp = substr(`"`temp'"',`=`next_dot'+1',.)
if index(`"`temp'"', ".")~=0 {
local next_dot = index(`"`temp'"',".")
local next_strip = substr(`"`temp'"',1,`=`next_dot'-1')
local strippedname = `"`strippedname'.`next_strip'"'
}
else {
* no change
local last_strip = `"`temp'"'
local change 1
}
}
*** check for manual rtf doc xlm xls csv extensions
if `"`last_strip'"'=="rtf" | `"`last_strip'"'=="doc" {
local word "word"
local file = `"`rabbit'`strippedname'.txt`rabbit'"'
local using = `"using `file'"'
local wordFile "`last_strip'"
}
if `"`last_strip'"'=="xls" | `"`last_strip'"'=="xml" | `"`last_strip'"'=="xlm" | `"`last_strip'"'=="csv" {
local excel "excel"
local file = `"`rabbit'`strippedname'.txt`rabbit'"'
local using = `"using `file'"'
local excelFile "`last_strip'"
}
if `"`last_strip'"'=="tex" {
if `"`tex1'"'=="" {
local tex "tex"
}
local file = `"`rabbit'`strippedname'.txt`rabbit'"'
local using = `"using `file'"'
local texFile "`last_strip'"
}
if `"`last_strip'"'=="txt" {
seeing `pref', `label'
}
else {
if "`using'"=="" {
di in red "must specify using file"
exit 198
}
seeing using `using', `label'
* similar to the other one except the clickable text
*local cl `"{stata `"seeout `pref'"': seeout `pref'}"'
*di as txt `"`cl'"'
}
else {
di in red "must specify the filename (the last preference has expired)"
exit 100
}
}
end
***********************
program define seeing
version 7.0
* invisible to Stata 7
local Version7 ""
cap local Version7 `c(stata_version)'
if "`Version7'"=="" {
* it is version 7
*noi di in yel "limited functions under Stata 7"
}
else if `Version7'>=8.2 {
version 8.2
}
quietly{
* syntax using/[, Clear]
syntax using [, LABel LABelA(string) ]
preserve
insheet `using', nonames clear
describe, short
* number of columns
local numcol = `r(k)'
tempvar blanks rowmiss
count if v1=="EQUATION"
if `r(N)'~=0 {
local eqPlace 1
local varPlace 2
count if v3=="LABELS"
if `r(N)'~=0 {
local labPlace 3
local num=4
}
else {
local labPlace 0
local num=3
}
}
else {
local eqPlace 0
local varPlace 1
count if v2=="LABELS"
if `r(N)'~=0 {
local labPlace 2
local num=3
}
else {
local labPlace 0
local num=2
}
}
gen int `blanks' = (trim(v`num')=="")
forvalues col = `num'/`numcol' {
replace `blanks' = `blanks' & (trim(v`col')=="")
}
* title rows
local titleWide = 0
if v1[1]~="" | v2[1]~="" {
* there may be a title
if `labPlace'==0 & `varPlace'==1 {
while v1[`=`titleWide'+1']~="" & v2[`=`titleWide'+1']=="" {
local titleWide = `titleWide'+1
}
}
if `labPlace'==0 & `varPlace'==2 {
while v2[`=`titleWide'+1']~="" & v3[`=`titleWide'+1']=="" {
local titleWide = `titleWide'+1
}
}
if `labPlace'~=0 & `varPlace'==1 {
while v1[`=`titleWide'+1']~="" & v3[`=`titleWide'+1']=="" {
local titleWide = `titleWide'+1
}
}
if `labPlace'~=0 & `varPlace'==2 {
while v2[`=`titleWide'+1']~="" & v4[`=`titleWide'+1']=="" {
local titleWide = `titleWide'+1
}
}
}
*local VARIABLES "VARIABLES"
* first name AFTER titles is the VARIABLES
local content
local num=`titleWide'+1
local N=_N
while `"`content'"'=="" & `num'<=`N' {
local content=v`varPlace'[`num']
local num=`num'+1
}
local VARIABLES `"`content'"'
replace `blanks'=0 if v1==`"`VARIABLES'"' | v1[_n-1]==`"`VARIABLES'"' | v2==`"`VARIABLES'"' | v2[_n-1]==`"`VARIABLES'"'
* getting bottomBorder (the bottom border), count up
gen rowmiss=0
foreach var of varlist v* {
replace rowmiss=rowmiss+1 if `var'~=""
}
local N=_N
local content 1
local num 0
while `content'==1 & `num'<`N' {
local content rowmiss[`=`N'-`num'']
local num=`num'+1
}
* do not have to add to titleWide
local bottomRow = `N'-`num'+1
local bottomBorder=`bottomRow'
* getting halfway to headBorder (the top border), count down
local content
local num=`titleWide'+1
local N=_N
while `"`content'"'=="" & `num'<=`N' {
local content=v`varPlace'[`num']
local num=`num'+1
}
* do not have to add to titleWide
local headRow `num'
local headBorder=`headRow'
drop rowmiss
* avoid counting space within each statistics row as missing
replace `blanks'=0 if `blanks'[_n+1]==0 & `blanks'==1 & _n >`titleWide'
* statistics rows
*count if `blanks'==0
*local bottomBorder = `r(N)'+`titleWide'
* move the notes and titles to the top of a new column
gen str5 Notes_Titles=""
format Notes_Titles %-20s
count if v1=="EQUATION"
if `r(N)'==0 {
* EQUATION column does not exist
if `titleWide'>0 {
forval num=1/`titleWide' {
replace Notes_Titles=v1[`num'] in `num'
replace v1="" in `num'
}
}
local one = 1
local legend = v1[`bottomBorder'+`one']
local place 1
*while "`legend'"~="" {
local N=_N
while `place' <= `N' {
local place=`bottomBorder'+`one'
local legend = v1[`place']
replace Notes_Titles="`legend'" in `=`one'+`titleWide'+1'
if "`legend'"~="" {
replace v1="" in `place'
}
local one = `one'+1
}
* insert label changes here, minus 2 from c(k) for `blanks' & Notes_Titles column
if "`label'"=="label" {
*if ("`long'"~="long" & "`onecol'"~="onecol") | ("`long'"=="long" & "`onecol'"=="onecol") {
replace v2=v1 if v2==""
drop v1
describe, short
forval num=1/`=`r(k)'-2' {
ren v`=`num'+1' v`num'
}
* change LABELS to VARIABLES
replace v1=`"`VARIABLES'"' if v1=="LABELS"
*}
local label_adjust "-1"
}
* change the string length
gen str5 temp=""
replace temp=v1
drop v1
ren temp v1
order v1
* format
foreach var of varlist v1 {
local _format= "`: format `var''"
local _widths=substr("`_format'",2,length(trim("`_format'"))-2)
format `var' %-`_widths's
}
}
else {
* equation column exists
if `titleWide'>0 {
forval num=1/`titleWide' {
replace Notes_Titles=v2[`num'] in `num'
replace v2="" in `num'
}
}
local one = 1
local legend = v2[`bottomBorder'+`one']
while "`legend'"~="" {
local place=`bottomBorder'+`one'
local legend = v2[`place']
replace Notes_Titles="`legend'" in `=`one'+`titleWide'+1'
if "`legend'"~="" {
replace v2="" in `place'
}
local one = `one'+1
}
* insert label changes here, minus 2 from c(k) for `blanks' & Notes_Titles column
if "`label'"=="label" {
*else if "`long'"~="long" & "`onecol'"=="onecol" {
replace v3=v2 if v3==""
drop v2
describe, short
forval num=2/`=`r(k)'-2' {
ren v`=`num'+1' v`num'
}
* change LABELS to VARIABLES
replace v2=`"`VARIABLES'"' if v2=="LABELS"
*}
local label_adjust "-1"
}
* change the string length
gen str5 temp=""
replace temp=v2
drop v2
ren temp v2
order v1 v2
* format
foreach var of varlist v1 v2 {
local _format= "`: format `var''"
local _widths=substr("`_format'",2,length(trim("`_format'"))-2)
format `var' %-`_widths's
}
}
* clean up
*egen `rowmiss'=rowmiss(_all)
* rowmiss option not available in 8.2 or 8.0, do it by hand
gen `rowmiss'=0
foreach var of varlist _all {
if "`var'"~="`rowmiss'" & "`var'"~="`blanks'" {
replace `rowmiss'=1+`rowmiss' if `var'==""
}
}
*drop if `rowmiss'==`numcol'+1
* adjust to handle label column droppings
*drop if `rowmiss'==`numcol'+1 & `blanks'==1
* fix blanks==1 for groupvar( )
count if `blanks'==1
local rN=`r(N)'+1
forval num=1/`rN' {
replace `blanks'=0 if `blanks'[_n+1]==0 & `blanks'==1
}
drop if `rowmiss'==`numcol'+1 `label_adjust' & `blanks'==1
drop `blanks' `rowmiss'
browse
if "`Version7'"=="" {
* it is version 7
}
else if `Version7'>=11.0 {
noi di in yel "Hit Enter to continue" _request(junk)
}
*restore, preserve
}
end /* end of seeing */
exit
* versions
1.1 replaced rowmiss option in egen, which is not available in 8.2
1.1.1 disabled -restore, preserve- as redundant waste of time
fixed seeing/seeout: handles blank space in stat(aster)
label does not show
no longer produces a seeout blue text whenever a seeout blue text was clicked
1.1.2 the shorthand form of seeout hides label
1.1.3 the shorthand form of seeout hides label: `label' is actually read from outreg2_pref.ado
1.2.0 down to version 7.0; -describe, short- instead of c(k)
if `"`using'"'~="": needed the compound quotes
VARIABLES is flexibly named
1.2.1 Apr2009 handles xls, doc, etc, that was left attached to file names in pref_ado
1.2.2 04Aug2009 a fix for asynchronoous data browser in -seeing- for version 11
1.2.3 21oct2009 outreg2_pref should have been replaced with outreg2.pref earlier

View File

@ -0,0 +1,59 @@
{smcl}
{* Oct 2005}{...}
{cmd:help seeout}
{hline}
{title:Title}
{p2colset 5 16 22 2}{...}
{p2col :{hi: seeout} {hline 2}}Opens tab-delimited {helpb outreg2} table in the data browser {p_end}
{p2colreset}{...}
{title:Syntax}
{p 4 8 2}
{cmdab:seeout} [,using {it:filename}] {p_end}
{pstd}
where a {it:filename} is a document to be opened. A minimum of two tabl-delimited columns
are required for a document to be opened. {p_end}
{title:Description}
{pstd}{cmd:seeout} will open a tab-delimited file created by {helpb outreg2} in the Stata data
browser. It is designed to provide a fast access to the regression table without first having to
convert the document into another format. {cmd:seeout} thus increasing the utility of such tables
in iterative research.
{pstd}If {cmd:seeout} is invoked immediately following an {helpb outreg2} command, then it is not
necessary to specify the using {it:filename}. It will be automatically opened.
{pstd}If no extension is provided, then .txt is assumed.
{title:Examples}
{phang}{cmd:seeout using mytable} {p_end}
{phang}{cmd:seeout using "c:\myfolder\mypaper.txt"} {p_end}
{phang}{cmd:outreg2 using mytable} {p_end}
{phang}{cmd:seeout} {p_end}
{title:Author}
Roy Wada
roywada@hotmail.com

View File

@ -0,0 +1,118 @@
program def sellist, rclass
*! NJC 1.5.0 30 November 2000
* NJC 1.4.0 5 Sept 2000
* NJC 1.3.0 7 June 2000
* NJC 1.2.0 31 Jan 2000
* NJC 1.1.0 22 Dec 1999
* NJC 1.0.0 22 Sept 1999
version 6.0
gettoken list 0 : 0, parse(",")
if "`list'" == "" | "`list'" == "," {
di in r "nothing in list"
exit 198
}
syntax , Select(str) /*
*/ [ PREfix SUFfix POSTfix Exact Noisily Global(str) All ]
if length("`global'") > 8 {
di in r "global name must be <=8 characters"
exit 198
}
if "`exact'" != "" & "`all'" != "" {
di in r "all option not allowed with exact option"
exit 198
}
if "`postfix'" != "" { local postop "postfix" }
else if "`suffix'" != "" { local postop "suffix" }
if "`postop'" != "" & "`prefix'" != "" {
di in r "choose between `postop' and prefix options"
exit 198
}
if "`postop'`prefix'" != "" & "`exact'`all'" != "" {
di in r /*
*/ "`postop'`prefix' option not allowed with `exact'`all' option"
exit 198
}
tokenize `list'
local nwords : word count `list'
local i = 1
while `i' <= `nwords' {
local len = length("``i''")
if `len' > 80 {
di in r "cannot handle word length > 80"
exit 498
}
local i = `i' + 1
}
tknz `select', s(s)
local ns : word count `select'
if "`prefix'`postop'" != "" & `ns' > 1 {
di in r /*
*/ "select( ) should contain one word with `prefix'`postop' option"
exit 198
}
if "`exact'" != "" {
while "`1'" != "" {
local i = 1
local OK = 0
while `i' <= `ns' & !`OK' {
local OK = "`1'" == "`s`i''"
local i = `i' + 1
}
if `OK' { local newlist "`newlist' `1'" }
mac shift
}
}
else {
while "`1'" != "" {
local i = 1
local OK = 0
while `i' <= `ns' {
local spos = /*
*/ length("`1'") - length("`s`i''") + 1
local where = index("`1'", "`s`i''")
if "`prefix'" != "" {
local thisOK = `where' == 1
}
else if "`postop'" != "" {
local thisOK = `where' == `spos'
}
else local thisOK = index("`1'", "`s`i''") > 0
local OK = `OK' + `thisOK'
local i = `i' + 1
}
if "`all'" != "" { local OK = `OK' == `ns' }
if `OK' { local newlist "`newlist' `1'" }
mac shift
}
}
if "`noisily'" != "" { di "`newlist'" }
if "`global'" != "" { global `global' "`newlist'" }
return local list `newlist'
end
program def tknz, rclass
* NJC 1.1.0 2 June 2000
version 6.0
gettoken list 0 : 0, parse(",")
syntax , Stub(str) [ * ]
tokenize `"`list'"' , `options'
local i = 1
while "``i''" != "" {
c_local `stub'`i' `"``i''"'
local i = `i' + 1
}
end

View File

@ -0,0 +1,2 @@
.h listutil

View File

@ -0,0 +1,35 @@
program def seqlist, rclass
*! NJC 1.2.0 4 July 2000
* NJC 1.1.0 7 June 2000
* NJC 1.0.0 31 Jan 2000
version 6.0
gettoken stub 0 : 0, parse(" ,")
if "`stub'" == "," {
local 0 ", `0'"
local stub
}
syntax , Copies(int) /*
*/ [ Noisily Start(int 1) Prefix Global(str) POSTfix(str) ]
if length("`global'") > 8 {
di in r "global name must be <=8 characters"
exit 198
}
local prefix = "`prefix'" != ""
local i = 1
local j = `start'
while `i' <= `copies' {
if `prefix' {
local newlist "`newlist'`j'`stub'`postfix' "
}
else local newlist "`newlist'`stub'`j'`postfix' "
local i = `i' + 1
local j = `j' + 1
}
if "`noisily'" != "" { di "`newlist'" }
if "`global'" != "" { global `global' "`newlist'" }
return local list `newlist'
end

View File

@ -0,0 +1,2 @@
.h listutil

View File

@ -0,0 +1,79 @@
*! shellout 1.4 04Aug2008
*! by roywada@hotmail.com
*! originally written to accompany -outreg2-
*
* version history
* 1.0 Oct2005 beta
* 1.1 Nov2007 opens an application without document name
* opens a document with or without "using"
* 1.2 Jan2008 cd option
* 1.3 Aug2008 version 7.0
* 1.4 04Aug2008 version 7.0 fiddling (was 1.3 Aug2008); fiddling with non-.txt suffix being recognized
program define shellout
version 7.0
syntax [anything] [using/] [,cd]
* does the shelling
if "`c(os)'"=="Windows" | "$S_MACH"=="PC" {
if "`using'"~="" {
winexec cmd /c start "" "`using'"
}
else {
if "`cd'"~="cd" {
cap winexec `anything'
if _rc==193 {
winexec cmd /c start "" "`anything'"
}
if _rc==601 {
noi di in yel "Cannot find `anything'. Make sure typed the name correctly."
}
}
else {
winexec cmd /c cd `c(pwd)'\ & `anything'
}
}
}
else {
* invisible to Stata 7
local Version7 ""
cap local Version7 `c(stata_version)'
if "`Version7'"=="" {
* stata 7
}
else {
* non-PC systems
di "{opt shellout} probably will not work with `c(os)'"
shell `using'
}
}
end
/* Old codes
* shellout
* version 1.0
* October 2005
* by roywada@hotmail.com
*
* (to accompany -outreg2-)
*
program define shelling
version 8.2
syntax using/
* does the shelling
*if c(machine_type)=="PC" {
if "`c(os)'"=="Windows" {
winexec cmd /c start "" "`using'"
}
else {
di "{opt shellout} probably will not work with `c(os)'"
shell `using'
}
end

View File

@ -0,0 +1,98 @@
{smcl}
{* Nov2005}{...}
{cmd:help shellout}
{hline}
{title:Title}
{p2colset 5 17 22 2}{...}
{p2col :{hi: shellout} {hline 2}}Opens documents and their programs from inside Stata. {p_end}
{p2colreset}{...}
{title:Multiple Syntax}
{p 4 8 2}
{cmdab:shellout} {it:application} [, cd] {p_end}
{pstd}
where {it:application} is the name of a software application to be opened. {p_end}
{p 4 8 2}
{cmdab:shellout} [using] {it:filename} [, cd] {p_end}
{pstd}
where {it:filename} takes the form of a document with a known extension, such as .doc,
.do, .dta, .txt, .xls, .xml, etc. {p_end}
{title:Options}
{pstd}{opt cd} should not be used, except to tell Stata that the program
in question is located in the current directory. {p_end}
{title:Description}
{pstd}{cmd:shellout} opens a document from inside Stata without having to specify the exact
file path of the program. It also opens an application with or without specifying a file
document to be opened.
{pstd}{cmd:shellout} is a {help shell} wrapper designed for Windows XP/NT. Unlike {help shell}, implements a nested DOS command. The DOS Window is told to close itself.
{pstd}{cmd:shellout} was originally written to accompany {helpb outreg2} for automatic opening
of non-Stata documents.
{title:Examples}
{phang}{cmd:shellout} wsestata.exe {p_end}
{phang}{cmd:shellout} using myfile.xml {p_end}
{phang}{cmd:shellout} using "c:\myfolder\myfile.doc" {p_end}
{phang}{cmd:shellout} myfile.xml {p_end}
{phang}{cmd:shellout} me.do {p_end}
{pstd}The first line will open another Stata executable. {p_end}
{pstd}The second line will open a document named myfile.xml in Excel. {p_end}
{pstd}The third line will open a document named myfile.doc in Word. {p_end}
{pstd}The fourth line will do the same thing without invoking the "using" syntax. {p_end}
{pstd}The fifth line is the equivalent of -do me- in another Stata executable, or was it -run me-.... {p_end}
{title:Parameters}
{pstd}A parameter is any value passed into a batch script. {cmd:shellout} will work with
parameters in the following examples (assuming you have Stata SE) {p_end}
{phang}{cmd:shellout} shellout wsestata.exe shellout wsestata.exe shellout wsestata.exe {p_end}
{phang}{cmd:shellout} wsestata di "Bite Me" {p_end}
{phang}{cmd:shellout} notepad "Bite Me" {p_end}
{pstd}The first line will open three Stata executables in a daisy-chain. {p_end}
{pstd}The second line will open a Stata executable with a "Bite Me" message. {p_end}
{pstd}The third line will open a (new) notepad file called "Bite Me". {p_end}
{title:Advanced Parameters}
{pstd}You can save a batch of parameters in a file and invoke it under {cmd:shellout}
much like calling upon a do-file. Learn some DOS commands if you want to implement it. {p_end}
{title:Author}
Roy Wada
roywada@hotmail.com
{title:Also see}
{p 9}{bf:[D] Shell} {p_end}

View File

@ -0,0 +1,106 @@
*! usesasdel Version 2.0 dan.blanchette@duke.edu 16Mar2009
*! Center of Entrepreneurship and Innovation Duke University's Fuqua School of Business
** shortdir Version 2.0 dan_blanchette@unc.edu 17Jan2008
** research computing, unc-ch
* - added check that if forward slashes used as dir separators
* then that is handled by converting them to back slashes
* - uses Nick Cox's way of loading a text file line by line
* into a local macro instead of reading it in as a dataset
** shortdir Version 1.1 dan_blanchette@unc.edu 28Oct2004
* - added test that directory actually exists
** shortdir Version 1.0 dan_blanchette@unc.edu 09Oct2003
** the carolina population center, unc-ch
program define shortdir, rclass
version 8
syntax using/ [, SHort ]
confirmdir "`using'"
if _rc !=0 {
di `"{error}The directory "`using'" does not exist."'
exit _rc
}
if "`c(os)'"=="Windows" {
preserve
local cwd "`c(pwd)'`macval(\\\)'"
if "`using'"=="." {
local using "`macval(cwd)'"
}
if "`using'"=="`cwd'" {
quietly cd ..
}
// check if forward slashes used and replace them if so
local subtest : subinstr local using `"/"' `""' , count(local cnt)
if `cnt' != 0 {
local using : subinstr local using "/" "\" , all
}
tokenize "`using'" , parse("\")
local i=1
while "``i''" !="" {
if `i'==1 {
local path "`1'"
}
else {
if "`short'"=="short" { /* create macro that conditionally checks
* for longer than 8 letter directory names */
local gt8=(length("``i''")>8)
local gt8="| `gt8'"
}
if index("``i''"," ") `gt8' { /* if sub dir name has space in name or maybe longer than 8 */
tempfile temp
_getfilename "`temp'"
local tfilen "`r(filename)'"
local tfileh=substr("`tfilen'",1,index("`tfilen'",".")-1) /* create file handle */
quietly {
cd "`path'\"
// options /x and /a create a short directory listing
// so `temp' is a very small, short file
! dir /x /a "``i''"* > "`temp'"
tempname in
file open `in' using `"`temp'"', r
file read `in' line
local dline ""
local dir "<DIR>"
while r(eof) == 0 {
// local line: subinstr local line "`old'" "`new'"
file read `in' line
if `: list local(dir) in local(line) ' {
local dline `"`line'"'
}
}
local gotit = 0
local shortname ""
local n = 1
while `gotit' == 0 {
local shortname : word `n' of `dline'
if `: list local(shortname) == local(dir) ' {
// the shortname of the subdir is the next word after "<DIR>"
local shortname : word `= `n' + 1' of `dline'
local gotit = 1
}
local n = `n' + 1
}
}
local sdir`i'=trim(substr(`"`shortname'"',1,10))
} /* end of if directory has a space */
else {
local sdir`i' "``i''"
}
if "``i''"!="\" {
local path "`macval(path)'\\`sdir`i''"
}
} /* if not the beginning of the path, like c: */
local i=`i'+1
} /* end of while loop */
quietly cd "`macval(cwd)'\\\"
local shortdir="`path'"+"\"
return local shortdir `shortdir'
} /* end of if windows */
else {
di "{error}shortdir only works in Windoze."
exit
}
end

View File

@ -0,0 +1,77 @@
{smcl}
{*! 17Jan2008}{...}
{* 06Nov2003}{...}
{hline}
help for {hi:shortdir} {right:manual: {hi:[R] none}}
{right:dialog: {hi: none} }
{hline}
{title:Returns the short directory name in `r(shortdir)'}
{p 8 17 2}{cmd:shortdir}
{it:using}{it:"directory path"}
[{cmd:,} {cmdab:sh:ort}]{p_end}
{title:Description}
{p 4 4 2}{cmd:shortdir} is designed for programmers using Stata on the Windows
operating system who want to know what the short directory
name (a.k.a. "8.3" name) that DOS names a directory when it contains spaces in the name or
has more than 8 characters in the name. This command only works in Windows because it
shells out to a DOS prompt in order to get the short directory name that Windows came
up with. The formula "Take the first 6 non-space characters and add '~1'" to the directory
name does not reliably work in all situations.{p_end}
{title:Examples}
{p 4 8 2}{cmd:shortdir "c:\Documents and Settings\dan\Local Settings\temp"}{p_end}
{p 4 8 2}returns in {cmd:r(shortdir)}:{p_end}
{p 4 8 2}{cmd:"c:\Docume~1\dan\LocalS~1\temp"}{p_end}
{p 4 8 2}{cmd:shortdir "c:\Documents and Settings\dan_blanchette\Local Settings\temp"}{p_end}
{p 4 8 2}returns in {cmd:r(shortdir)}:{p_end}
{p 4 8 2}{cmd:"c:\Docume~1\dan_blanchette\LocalS~1\temp"}{p_end}
{p 4 8 2}since "dan_blanchette" has no spaces in the name.{p_end}
{p 4 8 2}{cmd:shortdir "c:\Documents and Settings\dan_blanchette\Local Settings\temp", short}{p_end}
{p 4 8 2}returns in {cmd:r(shortdir)}:{p_end}
{p 4 8 2}{cmd:"c:\Docume~1\dan_bl~1\LocalS~1\temp"}{p_end}
{p 4 8 2}since "dan_blanchette" is longer than 8 characters.{p_end}
{title:Saved Results}
{p 4 4 2}The {cmd:shortdir} command saves in {cmd:r()}:{p_end}
{synoptset 20 tabbed}{...}
{p2col 5 20 24 2: Macros}{p_end}
{synopt:{cmd:{cmd:r(shortdir)}}the directory path.{p_end}
{title:Author}
{p 4 4 2}
Dan Blanchette {break}
Center of Entrepreneurship and Innovation {break}
Duke University's Fuqua School of Business {break}
Dan.Blanchette@Duke.edu{p_end}
{title:Also see}
{p 4 13 2}On-line: {help tempfile} {help _getfilename} ,
{help confirmdir} (if installed)
{help tmpdir} (if installed){p_end}

View File

@ -0,0 +1,200 @@
*! version 1.2.1 20dec2005
program define sjlatex
version 7
gettoken cmd 0 : 0, parse(" ,")
local l = length(`"`cmd'"')
preserve
if `"`cmd'"' == "" | `"`cmd'"' == "using" {
Using `cmd' `0'
di
}
else if `"`cmd'"' == substr("query",1,max(1,`l')) {
Query `0'
}
else if `"`cmd'"' == substr("install",1,max(1,`l')) {
Install `0'
}
else if `"`cmd'"' == substr("update",1,max(1,`l')) {
capture syntax [using] [, replace * ]
Install `using', replace `options'
}
else if `"`cmd'"' == substr("ado",1,max(1,`l')) {
if _caller() >= 9 {
di as txt /*
*/ "Use the {helpb adoupdate} command to update {cmd:sjlatex} and {cmd:sjlog}"
exit
}
Ado `0'
}
else {
di as error `"unrecognized command: `cmd'"'
exit 198
}
exit
end
/* get the SJ parameters */
program define GetParams, sclass
sreturn local from http://www.stata-journal.com/production
sreturn local pkg sjlatex
sreturn local src sjlatex
end
program define Using, rclass
local pwd : pwd
syntax [using/]
if `"`using'"' != "" {
quietly cd `"`using'"'
local sjdir : pwd
}
local cwd : pwd
di as txt _n "Stata Journal LaTeX files"
di as txt _col(5) "folder:" _col(25) as res `"`cwd'"'
di as txt _col(5) "installed release:" _col(25) _c
/* The top line of this file is an example of the form of the
* sj.version file.
*/
capture infile str20 version using sj.version
if _rc {
di as res "(unknown)"
}
else {
capture {
assert version[1] == "*!"
assert version[2] == "version"
}
if _rc {
di as res "(unknown)"
}
else {
di as res "version " version[3] " " version[4]
return local sjver = version[3]
return local sjdate = version[4]
}
}
return local sjdir `sjdir'
qui cd `"`pwd'"'
end
program define Query, rclass
syntax [using] [, norecommend from(string) ]
Using `using'
if `"`r(sjdir)'"' != "" {
local uusing `" using `"`r(sjdir)'"'"' /*"'*/
}
local sjdate `r(sjdate)'
local sjver `r(sjver)'
GetParams
if `"`from'"' == "" {
local from `s(from)'
}
local pkg `s(pkg)'
local src `s(src)'
tempfile sj_version
qui copy `"`from'/`src'/sj.version"' `sj_version', text
qui infile str20 version using `sj_version', clear
di as txt _col(5) "latest release:" _col(25) /*
*/ as res "version " version[3] " " version[4]
local l_sjver = version[3]
local l_sjdate = version[4]
if `"`recommend'"' == "" {
di as txt _n "{p 0 5}Recommendation{break}"
if `"`sjver'`sjdate'"' == "" {
di as txt `"type -{cmd:sjlatex install`uusing'}-"'
return local recommend install
}
else if `"`sjver'`sjdate'"' != `"`l_sjver'`l_sjdate'"' {
di as txt `"type -{cmd:sjlatex update`uusing'}-"'
return local recommend update
}
else {
di as txt `"Do nothing; all files up-to-date."'
}
}
end
program define Install
syntax [using/] [, replace from(string) noLS ]
if `"`using'"' != "" {
local uusing `" using `using'"'
}
local pwd : pwd
if `"`replace'"' == "" {
di as txt "Installing Stata Journal LaTeX files..."
if `"`using'"' != "" {
capture mkdir `"`using'"'
if _rc {
di as err /*
*/ `"could not create directory `using'"'
di as txt /*
*/ `"{p 0 4 2}This directory already existed."' /*
*/ `"Consider supplying an alternate directory or{break}"' /*
*/ `"type -{cmd:sjlatex update`uusing'}-.{p_end}"'
exit _rc
}
qui cd `"`using'"'
}
}
else {
di as txt "Updating Stata Journal LaTeX files..."
if `"`using'"' != "" {
quietly cd `"`using'"'
}
}
local sjdir : pwd
set more off
GetParams
local src `s(src)'
if `"`from'"' == "" {
local from `s(from)'
}
capture net from `"`from'"'
capture net get `src', `replace'
if _rc {
di as error `"could not copy the files to `sjdir'"'
if `"`replace'"' == "" {
di as txt `"{p}One or more files in this directory is in conflict with the Stata Journal LaTeX files. Consider supplying an alternate directory or{break}type -{cmd:sjlatex update`uusing'}-.{p_end}"'
}
else {
di as txt `"This directory may not be writable. Consider supplying an alternate directory."'
}
exit _rc
}
if "`c(stata_version)'" == "" {
capture /*
*/ cp `"`from'/`src'/statapress.cls"' statapress.cls, /*
*/ replace text
}
Using
if `"`replace'"' == "" & `"`ls'"' == "" {
di as input _n ". ls"
ls
}
if `"`uusing'"' != "" {
di as input _n ". pwd"
pwd
}
di in smcl as txt _n "{p 0 0 2}" /*
*/ "See the Getting Started instructions" /*
*/ " in the Remarks section of the online" /*
*/ " documentation for {help sjlatex}.{p_end}"
end
program define Ado
set more off
GetParams
local from `s(from)'
local pkg `s(pkg)'
quietly net from `"`from'"'
capture net install `pkg'
if _rc {
di as txt "updating package {cmd:sjlatex} package"
quietly ado uninstall `pkg'
quietly net install `pkg'
}
else di as txt "package {cmd:sjlatex} is up-to-date"
end
exit

View File

@ -0,0 +1,268 @@
{smcl}
{* *! version 1.0.1 11jan2006}{...}
{cmd:help sjlatex}{...}
{right:also see: {help sjlog}}
{hline}
{title:Title}
{pstd}
{hi:sjlatex} {hline 2} Downloading LaTeX files for the Stata Journal
{title:Syntax}
{phang2}
{cmd:sjlatex} [ {cmd:using} {it:dirname} ]
{phang2}
{cmd:sjlatex} {cmdab:q:uery} [ {cmd:using} {it:dirname} ]
{phang2}
{cmd:sjlatex} {cmdab:i:nstall} [ {cmd:using} {it:dirname} ] [, {cmd:replace} ]
{phang2}
{cmd:sjlatex} {cmdab:u:pdate} [ {cmd:using} {it:dirname} ]
{phang2}
{cmd:sjlatex} {cmdab:a:do} {* !!: to be removed when official}
{pstd}
Note that directories containing spaces should be enclosed in quotes.
{title:Description}
{pstd}
The {cmd:sjlatex} command reports on the current release of the package of
LaTeX files developed for the Stata Journal and installs/updates this
package.
{phang}
{cmd:sjlatex} reports on the LaTeX files installed in {it:dirname}.
{phang}
{cmd:sjlatex {cmd:query}} reports on the LaTeX files installed in
{it:dirname} and displays the release number of the files at the
Stata Journal web site.
{phang}
{cmd:sjlatex install} installs the LaTeX files in {it:dirname}.
{phang}
{cmd:sjlatex update} updates the LaTeX files in {it:dirname}.
{phang}
{cmd:sjlatex ado} updates {cmd:sjlatex} and the other ado files that are
packaged with {cmd:sjlatex}. This subcommand is only necessary for Stata 8 or
older; otherwise, use the {help adoupdate} command released in Stata 9.
{title:Options}
{phang}
{cmd:using} {it:dirname} identifies a directory to be used in
{cmd:sjlatex} [ {cmd:query} | {cmd:install} | {cmd:update} ].
{cmd:sjlatex install} creates {it:dirname}. The default is to use the
current directory.
{phang}
{cmd:replace} ({cmd:sjlatex} {cmd:install} only) causes {cmd:sjlatex}
{cmd:install} to behave like {cmd:sjlatex update}.
{title:Remarks}
{pstd}
Remarks are presented under the headings
Getting Started with the Stata Journal
Running LaTeX
Downloading Examples
TeX Distributions
{title:Getting Started with the Stata Journal}
{pstd}
There is a getting started example packaged with the Stata Journal LaTeX
files. The driver (main.tex) for this example uses the Stata Press document
class (statapress.cls), the Stata Press page dimensions package
(pagedims.sty), the Stata Journal package (sj.sty), the Stata
package (stata.sty), and the Stata Journal bibliographic style
(sj.bst). Individuals that have access to recent distributions of TeX are
encouraged to use these files since they are ultimately used to generate the
Stata Journal in its printed and electronic forms.
{pstd}
An alternate driver (altmain.tex) is also supplied. This file uses the LaTeX2e
standard article document class along with sj.bst, sj.sty, and
stata.sty. This alternative driver is supplied with the hope that
compatibility will not be an issue; however, the page dimensions and font
sizes are different in this case.
{title:File Dependencies}
{pstd}
The Stata Press document class (statapress.cls) is based on the standard
book document class (book.cls) in your TeX distribution.
{phang}
statapress.cls also requires hyperref.sty, color.sty,
fancyhdr.sty, natbib.sty, makeidx.sty, showidx.sty, and
multind.sty.
{phang}
pagedims.sty requires calc.sty and calc.sty.
{phang}
sj.sty requires ifthen.sty and chapterbib.sty.
{phang}
stata.sty requires alltt.sty and pstricks.sty.
{pstd}
All of these packages are available in most "free" TeX distributions.
{pmore}
Unfortunately crop.sty, chapterbib.sty, and natbib.sty are not
present in OzTeX 4.0, but they are collected into the
{net search sjextra:sjextra} Stata package for download. If you are using
OzTeX, then you will have to copy these files into the directory containing
your journal insert. The docstrip documentation/source for crop.sty and
natbib.sty are also included in the sjextra package for copyright
purposes. This package can be found using the following command in Stata.
{pmore2}
{cmd:. net search} {net search sjextra:sjextra}
{pmore}
You must also change {cmd:newcenter} to {cmd:oldcenter} in main.tex.
{title:Running LaTeX}
{pstd}
Before you make any changes to main.tex (or altmain.tex) to include your
journal insert, you should test the files using the given example article
(readme.tex). In fact, the files are already set up to perform the test. In
the following, we assume that you will be using main.tex, but the instructions
are essentially the same if you use altmain.tex.
{pstd}
The LaTeX program on Unix machines and PCs is invoked at the command prompt,
so let {cmd:>} (greater than symbol) be the command prompt. The Stata prompt
is {cmd:.} (period). Macintosh distributions of TeX tend to be based on
menus, thus the spirit of the following instructions are equivalent.
{phang}
1. Install {cmd:sjlatex}. Then from within Stata, install the author tools
in a new directory. For example, you might try one of the following depending
upon your operating system.
{pmore}
PC Windows:{break}
{cmd:. sjlatex install using C:\sjtemp}
{pmore}
UNIX:{break}
{cmd:. sjlatex install using ~/sjtemp}
{pmore}
Macintosh:{break}
{cmd:. sjlatex install using ~:sjtemp}
{pmore}
Here {cmd:sjlatex} will indicated the version and date of the LaTeX files.
{phang}
2. At the command prompt, you can now run LaTeX on main.tex.
{pmore}
{inp:> latex main}{break}
{inp:> bibtex main}{break}
{inp:> latex main}{break}
{inp:> latex main}{break}
{inp:> dvips main.dvi -o main.ps}
{pmore}
The first command generates the auxiliary (aux) file for your journal insert.
The bibtex command uses the aux file from your journal insert (main.aux for
the example) to generate bibliographic citations and references. After bibtex,
two more latex runs are needed to ensure that cross references appear
correctly in the resulting dvi-file. The last command uses dvips to generate
a PostScript file from the dvi-file.
{pmore}
The above commands were placed in a script (included with the files downloaded
by {cmd:sjlatex}) for your convenience.
{pmore}
PC Windows:{break}
{inp:> doit.bat}
{pmore}
UNIX:{break}
{inp:> sh doit.sh}
{pstd}
The final result is main.ps, which can be viewed using Ghostscript (PC:
gsview, UNIX: ghostview or gv, Macintosh: view the dvi-file from the menu).
Provided your TeX distribution contains the required packages, and passed the
above test, you can use these files to write your journal insert. Just make a
change to main.tex so that it includes the file containing your journal insert
(instead of readme.tex), and you're ready to run LaTeX on main.tex.
{title:Downloading Examples}
{pstd}
The results of the above test (of main.tex and altmain.tex) have been
converted to PDF documents collected in the {net search sjxmpl:sjxmpl} Stata
package for download. This package can be found using the following command
in Stata.
{pmore}
{cmd:. net search} {net search sjxmpl:sjxmpl}
{title:TeX distributions}
{pstd}
The examples have been successfully tested using the following TeX
distributions.
{pmore}
PC Windows: {browse "http://www.miktex.org":MiKTeX} version 2.3 (Free)
{pmore}
UNIX: {browse "http://www.tug.org/tetex/":teTeX} versions 1.0 to 3.0 (Free)
{pmore}
Macintosh: {browse "http://www.trevorrow.com/oztex/":OzTeX} version 4.0
(Shareware), and {browse "http://www.kiffe.com/cmactex.html":CMacTeX}
version 4.0 (Shareware)
{pmore}
Macintosh OS X:
{browse "http://www.uoregon.edu/~koch/texshop/texshop.html":TeXShop}
version 1.40 (Free){p_end}
{pmore2}For compatibility with {cmd:sjlatex} and TeXShop, you must
enable the {hi:Typeset} -> {hi:TeX} and {hi:Ghostscript} mode.
{pstd}
The main web site for the Comprehensive TeX Archive Network (CTAN) is
{browse "http://www.tug.org/"}.
{pstd}
The main web site for Ghostscript is {browse "http://www.cs.wisc.edu/~ghost/"}.
{title:Also see}
{psee}
Online:
{help sjlog}
{p_end}

View File

@ -0,0 +1,501 @@
*! version 1.2.11 18feb2010
program define sjlog
if _caller() < 8.0 {
sjlog_7 `0'
exit
}
version 8.0
local vv : display _caller()
gettoken cmd 0 : 0, parse(" ,")
local l = length(`"`cmd'"')
if `"`cmd'"' == "using" | `"`cmd'"' == "open" {
LogOpen `0'
}
else if `"`cmd'"' == "close" {
LogClose `0'
}
else if `"`cmd'"' == "do" {
LogDo `vv' `0'
}
else if `"`cmd'"' == "clean" {
LogClean `0'
}
else if `"`cmd'"' == "type" {
LogType `0'
}
else if `"`cmd'"' == substr("basename",1,`l') {
LogBaseName `0'
}
else if `"`cmd'"' == "" {
log
}
else {
di as err "`cmd' invalid"
exit 198
}
end
program define LogSetup
syntax [, clear ]
if "`clear'" != "" {
clear
program drop _all
}
capture log close
set rmsg off
set more off
set trace off
end
program define StripQuotes
syntax anything(name=name id="name") [, string(string) ]
c_local `name' `"`string'"'
end
/* basename *****************************************************************/
program define LogBaseName, rclass
syntax anything(name=file id="filename") [, Display ]
StripQuotes file , string(`file')
local dirsep "/"
/* strip off the directory path */
gettoken dir rest : file, parse("/\:")
while `"`rest'"' != "" {
if `"`dir'"' == "\" {
local dir `"`dirsep'"'
}
local dirname `"`dirname'`dir'"'
gettoken dir rest : rest , parse("\/:")
}
if `"`dirname'"' == "" {
local dirname .`dirsep'
}
/* strip off the extension */
gettoken ext rest : dir, parse(".")
while `"`rest'"' != "" {
local basename `basename'`ext'
gettoken ext rest : rest , parse(".")
}
if `"`basename'"' == "" {
local basename `ext'
local ext
}
else {
/* remove the last "." from `basename' */
local l = length(`"`basename'"') - 1
local basename = substr(`"`basename'"',1,`l')
}
/* saved results */
return local ext = cond(`"`ext'"'=="","",".") + `"`ext'"'
return local base `"`basename'"'
return local dir `"`dirname'"'
return local fn `"`file'"'
if `"`display'"' != "" {
display as txt `"fn: `return(fn)'"'
display as txt `"dir: `return(dir)'"'
display as txt `"base: `return(base)'"'
display as txt `"ext: `return(ext)'"'
}
end
/* using/close/do: subroutines **********************************************/
program define LogOpen
syntax anything(name=file id="filename") [, append replace ]
LogSetup
LogBaseName `file'
local ext `"`r(ext)'"'
if `"`ext'"' != ".smcl" {
local file `"`r(fn)'.smcl"'
}
quietly log using `"`file'"', smcl `append' `replace'
end
program define LogClose, rclass
syntax [, /*
*/ book /*
*/ replace /*
*/ noCLEAN /*
*/ noLOGfile /*
*/ sjlogdo /* internal only, NOT documented
*/ ]
if `"`sjlogdo'"' == "" {
local logtype sjlog
}
else local logtype `sjlogdo'
quietly log
LogBaseName `"`r(filename)'"'
local dir `"`r(dir)'"'
local base `"`r(base)'"'
local ext `"`r(ext)'"'
local file `"`r(fn)'"'
local dbase `"`dir'`base'"'
quietly log close
/* log assumed to be a smcl file */
if `"`ext'"' != ".smcl" {
di in red "assumption failed -- log file not smcl"
exit 198
}
if `"`clean'"' == "" {
LogClean `"`file'"', `logtype'
erase `"`r(fnbak)'"'
}
/* get TeX version of log */
qui log texman `"`file'"' `"`dbase'.log.tex"', `replace' `book'
if `"`logfile'"' == "" {
/* get plain text version of log */
qui translate `"`file'"' `"`dbase'.log"', `replace'
}
/* saved results */
if `"`logfile'"' == "" {
return local fn_log `"`dbase'.log"'
}
return local fn_tex `"`dbase'.log.tex"'
return local fn_smcl `"`dbase'.smcl"'
end
program define LogDo
version 8.0
gettoken vv 0 : 0
local vv "version `vv':"
syntax anything(name=file id="filename") [, ///
clear ///
replace ///
book ///
nostop ///
SAVing(string) ///
]
if "`saving'" != "" {
capture confirm name `saving'
if _rc {
di as err ///
"'`saving'' found where saving() option requires a valid name"
exit 198
}
}
LogSetup, `clear'
LogBaseName `file'
local base = cond("`saving'"=="","`r(base)'","`saving'")
local dbase `"`r(dir)'`base'"'
local ext `"`r(ext)'"'
local file `"`r(fn)'"'
if `"`ext'"' != ".do" {
local dbase `"`dbase'`ext'"'
}
LogOpen `dbase', `replace'
capture noisily `vv' do `file', `stop'
local rc = _rc
if `rc' {
local cap capture
}
`cap' LogClose, `replace' sjlogdo `book'
exit `rc'
end
/* clean: subroutines *******************************************************/
program define LogClean, rclass
syntax anything(name=file id="filename") [, /*
*/ log /*
*/ logclose /*
*/ sjlog /*
*/ sjlogdo /*
*/ ]
/* validate arguments and options */
local logsrc `log' `logclose' `sjlog' `sjlogdo'
local wc : word count `logsrc'
if `wc' > 1 {
di as err "options `logsrc' may not be combined"
exit 198
}
StripQuotes file , string(`file')
confirm file `"`file'"'
/* open files */
tempname rf wf
tempfile newfile
file open `rf' using `"`file'"', read text
file open `wf' using `"`newfile'"', write text
/* clean file */
capture noisily {
if `"`logsrc'"' == "logclose" {
CleanLogclose `rf' `wf'
}
else if `"`logsrc'"' == "sjlog" {
CleanSJLog `rf' `wf'
}
else if `"`logsrc'"' == "sjlogdo" {
CleanSJLogDo `rf' `wf'
}
else { /* Default: `"`logsrc'"' == "log" */
CleanLog `rf' `wf'
}
} // capture noisily
local rc = _rc
/* close files */
file close `wf'
file close `rf'
if (`rc') exit `rc'
/* make a backup copy of the input file (rf) and save the output file
* (wf) using the given filename
*/
local backup `file'.bak
copy `"`file'"' `"`backup'"', replace
copy `"`newfile'"' `"`file'"', replace
/* saved results */
return local fnbak `"`backup'"'
return local fn `"`file'"'
end
/* Clean log produced by -sjlog do-.
*
* This subroutine has a 3 line buffer; the end of a log from -sjlog do- will
* always have:
*
* 1. a blank line
* 2. a line with the text: "."
* 3. a line with the text: "end of do-file"
*
* This subroutine also works with smcl files, and TeX files generated from
* smcl files using -log texman- (its original purpose).
*/
program define CleanSJLogDo
args rf wf
/* skip the smcl header lines */
file read `rf' line1
if `"`line1'"' == "{smcl}" {
file read `rf' line1
/* skip next line too, if is part of the smcl header */
if `"`line1'"' == "{com}{sf}{ul off}{txt}" {
file read `rf' line1
}
file read `rf' line2
}
else {
file read `rf' line2
}
file read `rf' line3
local break 0
while r(eof)==0 {
if substr(`"`line3'"',-14,.) == "end of do-file" {
local break 1
continue, break
}
file write `wf' `"`macval(line1)'"' _n
local line1 `"`macval(line2)'"'
local line2 `"`macval(line3)'"'
file read `rf' line3
}
if ! `break' {
file write `wf' `"`macval(line1)'"' _n
file write `wf' `"`macval(line2)'"' _n
}
else {
if !inlist(`"`macval(line1)'"',"{txt}","{res}{txt}") {
file write `wf' `"`macval(line1)'"' _n
}
}
end
/* Clean log produced by -sjlog using- and -sjlog close-. */
program define CleanSJLog
args rf wf
CleanLogUsingHeader `rf'
/* skip the smcl header lines */
file read `rf' line1
if `"`line1'"' == "{smcl}" {
file read `rf' line1
/* skip next line too, if is part of the smcl header */
if `"`line1'"' == "{com}{sf}{ul off}{txt}" {
file read `rf' line1
}
file read `rf' line2
}
else {
file read `rf' line2
}
local break 0
while r(eof)==0 {
if index(`"`line2'"',". sjlog close") {
local break 1
continue, break
}
file write `wf' `"`macval(line1)'"' _n
local line1 `"`macval(line2)'"'
file read `rf' line2
}
if ! `break' | !inlist(`"`macval(line1)'"', "", "{res}{txt}") {
file write `wf' `"`macval(line1)'"' _n
}
end
/* Clean log produced by Stata's -log using- and -log close- commands. */
program define CleanLog
args rf wf
CleanLogUsingHeader `rf'
file read `rf' line
local break 0
while r(eof)==0 {
/* stop when we encounter the -log close- command. */
if substr(`"`line'"',-11,.) == ". log close" {
local break 1
continue, break
}
file write `wf' `"`macval(line)'"' _n
file read `rf' line
}
end
/* Clean log produced by Stata's -log using- command and -logclose-. */
program define CleanLogclose
args rf wf
CleanLogUsingHeader `rf'
file read `rf' line
local break 0
while r(eof)==0 {
/* stop when we encounter the -log close- command. */
if substr(`"`line'"',-10,.) == ". logclose" {
local break 1
continue, break
}
file write `wf' `"`macval(line)'"' _n
file read `rf' line
}
end
/* Skip first 5 lines comprising the header output from -log using-. */
program define CleanLogUsingHeader
args rf
/* hline */
file read `rf' line
if `"`line'"' == "{smcl}" {
file read `rf' line
file read `rf' line
}
else if index(`"`line'"', "-----") {
file read `rf' line
}
if ! index(`"`line'"', "log:") {
file seek `rf' tof
exit
}
file read `rf' line
if ! index(`"`line'"', "log type:") {
file seek `rf' tof
exit
}
file read `rf' line
if ! index(`"`line'"', "opened on:") {
file seek `rf' tof
exit
}
/* blank line */
file read `rf' line
end
/* type: subroutines ********************************************************/
program define LogType, rclass
syntax anything(name=file id="filename") [, /*
*/ replace /*
*/ find /*
*/ path(passthru) /*
*/ LOGfile /*
*/ SMCLfile /*
*/ ]
LogSetup
if "`logfile'" == "" {
local logfile nologfile
}
StripQuotes file , string(`file')
if `"`find'"' != "" {
capture which findfile
if _rc {
di as err "option find requires Stata 8 or later"
exit 111
}
quietly findfile `"`file'"', `path'
local file `r(fn)'
}
LogBaseName `file'
local file `"`r(fn)'"'
local dbase `"`r(dir)'`r(base)'"'
local ext `"`r(ext)'"'
if ! inlist(`"`ext'"',".smcl",".hlp") {
local dbase `"`dbase'`ext'"'
}
capture noisily {
tempfile tt
LogOpen `tt'
type `"`file'"'
LogClose, noclean `logfile'
copy `"`tt'.log.tex"' `"`dbase'.log.tex"', `replace'
return local fn_tex `"`dbase'.log.tex"'
if "`logfile'" == "logfile" {
copy `"`tt'.log"' `"`dbase'.log"', `replace'
return local fn_log `"`dbase'.log"'
}
}
local rc = _rc
if "`smclfile'" != "" {
copy `"`tt'.smcl"' `"`dbase'.smcl"', `replace'
return local fn_smcl `"`dbase'.smcl"'
}
capture erase `"`tt'.smcl"'
capture erase `"`tt'.log.tex"'
exit `rc'
end
exit

View File

@ -0,0 +1,351 @@
{smcl}
{* *! version 1.0.0 20dec2005}{...}
{cmd:help sjlog}{...}
{right:also see: {help sjlatex}}
{hline}
{title:Title}
{pstd}
{hi:sjlog} {hline 2} Creating and managing logs for Stata Journal articles
{title:Syntax}
{phang2}
{cmd:sjlog} {it:subcmd} ...
{title:Opening and closing logs}
{phang2}
{cmd:sjlog} {cmd:using} {it:filename}
[,
{cmd:append} | {cmd: replace}
]
{phang2}
{cmd:sjlog} {cmd:close}
[,
{cmd:noclean}
{cmd:no}{cmdab:log:file}
{cmd:replace}
{cmd:book}
]
{title:Logging the results of a do-file}
{phang2}
{cmd:sjlog} {cmd:do} {it:filename}
[,
{cmd:clear}
{cmd:replace}
{cmd:book}
{cmd:nostop}
{cmdab:sav:ing:(}{it:basename}{cmd:)}
]
{title:Utilities}
{pstd}
Removing unwanted lines from a log.
{phang2}
{cmd:sjlog} {cmd:clean} {it:filename}
[,
{cmd:log} |
{cmd:logclose} |
{cmd:sjlog} |
{cmd:sjlogdo}
]
{pstd}
Copy a file to be included in an Stata Journal article.
{phang2}
{cmd:sjlog} {cmd:type} {it:filename}
[,
{cmd:replace}
{cmd:find}
{cmd:path(}{it:path}{cmd:)}
{cmdab:log:file}
{cmdab:smcl:file}
]
{pstd}
Split a file name into three parts.
{phang2}
{cmd:sjlog} {cmdab:base:name} {it:filename}
[,
{cmdab:d:isplay}
]
{pstd}
Note that filenames containing spaces should be enclosed in quotes.
{title:Description}
{pstd}
{cmd:sjlog} is a tool for Stata users who are writing documents that contain
Stata output. It was written to help authors of the Stata Journal.
{phang}
{cmd:sjlog} {cmd:using}/{cmd:close} open and close log files similar to the
log command, see help {help log}.
{phang}
{cmd:sjlog} {cmd:do} logs the output generated by the specified do-file.
{phang}
{cmd:sjlog} {cmd:clean} removes lines of text from {cmd:smcl} files. This
subcommand was added to facilitate the removal of the header and footer
generated by the {cmd:log} command, as well as the command that closed the
log.
{phang}
{cmd:sjlog} {cmd:type} makes a copy of a file with some substitutions to make
the file is suitable for inclusion in a TeX or LaTeX document.
{phang}
This subroutine facilitates the inclusion of do-files and ado-files in Stata
Journal articles without having to manually maintain duplicate copies of the
same file.
{phang}
{cmd:sjlog} {cmd:type} can also be used to copy {cmd:smcl} files to a format
suitable for inclusion in a TeX or LaTeX document provided you also have
stata.sty, a LaTeX package written for the Stata Journal. For more
information about LaTeX packages written for the Stata Journal, see help
{help sjlatex}.
{phang}
{cmd:sjlog} {cmd:basename} is something of a combination of the UNIX commands
{bf:basename} and {bf:dirname}. It simply splits the specified file into
three distinct parts:
{pmore}
1. the directory path (e.g. {cmd:/work/}, {cmd:C:\work\}){break}
2. the suffix (e.g. {cmd:.do}, {cmd:.log}, {cmd:.smcl}){break}
3. the basename (what is left over from 1 and 2)
{phang}
The {cmd:display} option causes {cmd:sjlog} {cmd:basename} to display the
results.
{title:Options for {cmd:sjlog} {cmd:using}/{cmd:close}/{cmd:do}}
{phang}
{cmd:append} ({cmd:sjlog} {cmd:using} only) allows the output to be appended
onto the end of an already existing file. See the {cmd:append} option in help
{help log}.
{phang}
{cmd:replace} (for all {cmd:sjlog} subroutines) indicates that exiting
{it:filename} (with a {cmd:.smcl}, {cmd:.log}, or {cmd:.log.tex} suffix) will
be overwritten.
{phang}
{cmd:noclean} ({cmd:sjlog} {cmd:close} only) prevents {cmd:sjlog} from
"cleaning" the {cmd:smcl} log before generating the plain text and TeX
version.
{phang}
{cmd:clear} ({cmd:sjlog} {cmd:do} only) causes {cmd:sjlog} to run
"{cmd}program drop _all{reset}" prior to running "{cmd:do} {it:filename}".
{phang}
{cmd:book} ({cmd:sjlog} {cmd:close}/{cmd:do} only) causes {cmd:sjlog} to use
special escape characters in the generated TeX file. This option is no longer
necessary, but was added to facilitate maintenance of legacy documents that
used the LaTeX listings environment to display Stata logs.
{phang}
{cmd:nostop} ({cmd:sjlog} {cmd:do} only) allows the do-file to continue
executing even if an error occurs.
{phang}
{cmd:saving(}{it:basename}{cmd:)} ({cmd:sjlog} {cmd:do} only) allows for the
logs to be saved to {it:basename}.smcl, {it:basename}.log, and
{it:basename}.log.tex, instead of using the 'basename' of the do-file.
{title:Options for {cmd:sjlog} {cmd:clean}}
{phang}
{cmd:log} (default) indicates that {it:filename} was created by {cmd:log}
{cmd:using} and {cmd:log} {cmd:close}. This results in the removal of the log
header and footer created by the {cmd:log} command (if they exist), as well as
the removal of the last executed command (and the preceding blank) if it is:
{pmore2}
{cmd}. log close{reset}
{phang}
{cmd:logclose} indicates that {it:filename} was created by {cmd:log}
{cmd:using} and {cmd:logclose}. This results in the removal of the log
header and footer created by the {cmd:log} command (if they exist), as well as
the removal of the last executed command (and the preceding blank) if it is:
{pmore2}
{cmd}. logclose{reset}
{phang}
{cmd:sjlog} indicates that {it:filename} was created by {cmd:sjlog}
{cmd:using} and {cmd:sjlog} {cmd:close}. This results in the removal of the
last executed command (and the preceding blank) if it is:
{pmore2}
{cmd}. sjlog close{reset}
{phang}
{cmd:sjlogdo} indicates that {it:filename} was created by {cmd:sjlog}
{cmd:do}. This results in the removal of the last line of output (and the
preceding blank) if it is:
{pmore2}
{cmd}end of do-file{reset}
{title:Options for {cmd:sjlog} {cmd:type}}
{phang}
{cmd:find} indicates that {it:filename} is somewhere on the ado path. This
option requires the {cmd:findfile} command introduced in Stata 8, see help
{help findfile}.
{phang}
{cmd:path()} specifies the path over which {cmd:findfile} is to search, see
the {cmd:path()} option description in help {help findfile}.
{phang}
{cmd:logfile} specifies that a plain text file also be created.
{phang}
{cmd:smclfile} specifies that a SMCL file also be created.
{title:Details: generating logs}
{pstd}
The logged output will be saved in three formats:
{phang}
1. The plain text log will have a {cmd:.log} suffix.
{break}
2. The smcl log will be saved with a {cmd:.smcl} suffix.
{break}
3. The TeX log will have a {cmd:.log.tex} suffix.
{pstd}
The TeX log utilizes some tailored TeX macros defined in stata.sty, a LaTeX
package designed for the Stata Journal.
{pstd}
Logs can be generated in one of two ways:
{phang}
(1) {cmd:sjlog} {cmd:using} {it:filename} turns Stata's logging on, and saves
the output to {it:filename}.
{pmore2}
It is recommended that {it:filename} not have a suffix; in any case, an
appropriate suffix will be supplied according to the above list.
{phang2}
{cmd:sjlog} {cmd:close} closes the current log.
{phang}
(2) {cmd:sjlog} {cmd:do} {it:filename} is almost exactly like running the
following commands:
{pmore2}
{cmd}
. sjlog using {it:filename}
{break}
. do {it:filename}.do
{break}
. sjlog close
{reset}
{phang}
where {it:filename} is the base name (having no suffix) of a Stata do-file,
except the command "{cmd}do {it:filename}.do{reset}" is removed from the log.
{pstd}
When you begin logging, {cmd:sjlog} will first close the current log (if there
is one) before opening a new log with the given options. Also the {help more}
and {help trace} settings are turned off.
{title:Details: copying files}
{pstd}
{cmd:sjlog} {cmd:type} is almost exactly like running the following commands:
{pmore2}
{cmd}
. sjlog using {it:filename}.tex
{break}
. type {it:filename}
{break}
. sjlog close
{reset}
{title:Saved results}
{pstd}
{cmd:sjlog} {cmd:close} saves in {cmd:r()}:
Macros
{cmd:r(fn)} name of the TeX log
{pstd}
{cmd:sjlog} {cmd:clean} saves in {cmd:r()}:
Macros
{cmd:r(fn)} {it:filename}
{cmd:r(fnbak)} {it:filename}.bak, backup copy of {it:filename}
{pstd}
{cmd:sjlog} {cmd:type} saves in {cmd:r()}:
Macros
{cmd:r(fn)} {it:filename}.tex, copy of {it:filename}
{pstd}
{cmd:sjlog} {cmd:basename} saves in {cmd:r()}:
Macros
{cmd:r(fn)} {it:filename}
{cmd:r(dir)} directory path of {it:filename}
{cmd:r(base)} basename of {it:filename}
{cmd:r(ext)} extension suffix of {it:filename}
{title:Also see}
{psee}
Manual:
{hi:[R] log},
{hi:[P] program},
{hi:[P] smcl},
{hi:[R] translate}
{p 4 13 2}
Online:
{help log},
{help program},
{help smcl},
{help translate}
{p_end}

View File

@ -0,0 +1,569 @@
*! version 1.1.13 06may2003
program define sjlog_7
version 7
local vv : di "version " _caller() ":"
gettoken cmd 0 : 0, parse(" ,")
local l = length(`"`cmd'"')
if `"`cmd'"' == "using" | `"`cmd'"' == "open" {
LogOpen `0'
}
else if `"`cmd'"' == "close" {
LogClose `0'
}
else if `"`cmd'"' == "do" {
`vv' LogDo `0'
}
else if `"`cmd'"' == "clean" {
LogClean `0'
}
else if `"`cmd'"' == "type" {
LogType `0'
}
else if `"`cmd'"' == substr("basename",1,`l') {
LogBaseName `0'
}
else if `"`cmd'"' == "" {
log
}
else {
di as err "`cmd' invalid"
exit 198
}
end
program define LogSetup
syntax [, clear ]
if "`clear'" != "" {
clear
program drop _all
}
capture log close
set rmsg off
set more off
set trace off
end
program define StripQuotes
syntax anything(name=name id="name") [, string(string) ]
c_local `name' `"`string'"'
end
/* basename *****************************************************************/
program define LogBaseName, rclass
syntax anything(name=file id="filename") [, Display ]
StripQuotes file , string(`file')
local dirsep "/"
/* strip off the directory path */
gettoken dir rest : file, parse("/\:")
while `"`rest'"' != "" {
if `"`dir'"' == "\" {
local dir `"`dirsep'"'
}
local dirname `"`dirname'`dir'"'
gettoken dir rest : rest , parse("\/:")
}
if `"`dirname'"' == "" {
local dirname .`dirsep'
}
/* strip off the extension */
gettoken ext rest : dir, parse(".")
while `"`rest'"' != "" {
local basename `basename'`ext'
gettoken ext rest : rest , parse(".")
}
if `"`basename'"' == "" {
local basename `ext'
local ext
}
else {
/* remove the last "." from `basename' */
local l = length(`"`basename'"') - 1
local basename = substr(`"`basename'"',1,`l')
}
/* saved results */
return local ext = cond(`"`ext'"'=="","",".") + `"`ext'"'
return local base `"`basename'"'
return local dir `"`dirname'"'
return local fn `"`file'"'
if `"`display'"' != "" {
display as txt `"fn: `return(fn)'"'
display as txt `"dir: `return(dir)'"'
display as txt `"base: `return(base)'"'
display as txt `"ext: `return(ext)'"'
}
end
/* using/close/do: subroutines **********************************************/
program define LogOpen
syntax anything(name=file id="filename") [, append replace ]
LogSetup
LogBaseName `file'
local ext `"`r(ext)'"'
if `"`ext'"' != ".smcl" {
local file `"`r(fn)'.smcl"'
}
quietly log using `"`file'"', smcl `append' `replace'
end
program define LogClose, rclass
syntax [, /*
*/ book /*
*/ replace /*
*/ noCLEAN /*
*/ noLOGfile /*
*/ sjlogdo /* internal only, NOT documented
*/ ]
if `"`sjlogdo'"' == "" {
local logtype sjlog
}
else local logtype `sjlogdo'
quietly log
LogBaseName `"`r(filename)'"'
local dir `"`r(dir)'"'
local base `"`r(base)'"'
local ext `"`r(ext)'"'
local file `"`r(fn)'"'
local dbase `"`dir'`base'"'
quietly log close
/* log assumed to be a smcl file */
if `"`ext'"' != ".smcl" {
di in red "assumption failed -- log file not smcl"
exit 198
}
if `"`clean'"' == "" {
LogClean `"`file'"', `logtype'
erase `r(fnbak)'
}
/* get TeX version of log */
qui log texman `"`file'"' `"`dbase'.log.tex"', `replace' `book'
if `"`logfile'"' == "" {
/* get plain text version of log */
qui translate `"`file'"' `"`dbase'.log"', `replace'
}
/* saved results */
if `"`logfile'"' == "" {
return local fn_log `"`dbase'.log"'
}
return local fn_tex `"`dbase'.log.tex"'
return local fn_smcl `"`dbase'.smcl"'
end
program define LogDo
version 7.0
local vv : display "version " _caller() ":"
syntax anything(name=file id="filename") [, /*
*/ clear /*
*/ replace /*
*/ book /*
*/ nostop /*
*/ SAVing(string) /*
*/ ]
if "`saving'" != "" {
capture confirm name `saving'
if _rc {
di as err /*
*/ "'`saving'' found where saving() option requires a valid name"
exit 198
}
}
LogSetup, `clear'
LogBaseName `file'
local base = cond("`saving'"=="","`r(base)'","`saving'")
local dbase `"`r(dir)'`base'"'
local ext `"`r(ext)'"'
local file `"`r(fn)'"'
if `"`ext'"' != ".do" {
local dbase `"`dbase'`ext'"'
}
LogOpen `dbase', `replace'
capture noisily `vv' do `file', `stop'
local rc = _rc
if `rc' {
local cap capture
}
`cap' LogClose, `replace' sjlogdo `book'
exit `rc'
end
/* clean: subroutines *******************************************************/
program define LogClean, rclass
syntax anything(name=file id="filename") [, /*
*/ log /*
*/ logclose /*
*/ sjlog /*
*/ sjlogdo /*
*/ ]
/* validate arguments and options */
local logsrc `log' `logclose' `sjlog' `sjlogdo'
local wc : word count `logsrc'
if `wc' > 1 {
di as err "options `logsrc' may not be combined"
exit 198
}
StripQuotes file , string(`file')
confirm file `"`file'"'
/* open files */
tempname rf wf
tempfile newfile
file open `rf' using `"`file'"', read text
file open `wf' using `"`newfile'"', write text
/* clean file */
capture noisily {
initMacros
if `"`logsrc'"' == "logclose" {
CleanLogclose `rf' `wf'
}
else if `"`logsrc'"' == "sjlog" {
CleanSJLog `rf' `wf'
}
else if `"`logsrc'"' == "sjlogdo" {
CleanSJLogDo `rf' `wf'
}
else { /* Default: `"`logsrc'"' == "log" */
CleanLog `rf' `wf'
}
}
local rc = _rc
/* close files */
file close `wf'
file close `rf'
removeMacros `rc'
/* make a backup copy of the input file (rf) and save the output file
* (wf) using the given filename
*/
local backup `file'.bak
copy `"`file'"' `"`backup'"', replace
copy `"`newfile'"' `"`file'"', replace
/* saved results */
return local fnbak `"`backup'"'
return local fn `"`file'"'
end
program define initMacros
global SJL_maxn 10
global SJL_n 0
global SJL_parity 0
end
program define removeMacros
args rc
if "$SJL_parity" != "0" & "$SJL_parity" != "" {
di as err "$SJL_parity nonempty global macros"
forval i = 1/$SJL_maxn {
if `"${SJL_`i'}"' != "" {
di _asis as txt /*
*/ `"SJL_`i' is |${SJL_`i'}{reset}{text}|"'
}
global SJL_`i'
}
if ! `rc' {
local rc 459
}
}
global SJL_parity
global SJL_maxn
global SJL_n
exit `rc'
end
program define removeLine
args line
global `line'
/* decrease number of lines read */
global SJL_parity = $SJL_parity - 1
end
program define FileRead
args hh c_line
/* read in line */
file read `hh' rline
/* increase number of lines read */
local n = mod($SJL_n,$SJL_maxn) + 1
/* increase parity index */
global SJL_parity = $SJL_parity + 1
/* escape quotes */
local qline : /*
*/ subinstr local rline "\`" "\\\`" , all count(local qc)
/* escape dollars */
global SJL_`n' : /*
*/ subinstr local qline "\$" "\\\$" , all count(local dc)
/* return name of global macro containing new line */
c_local `c_line' SJL_`n'
/* save number of lines read */
global SJL_n `n'
end
program define FileWrite
args hh line
/* write contents of global to file */
file write `hh' `"${`line'}"' _n
removeLine `line'
end
/* Clean log produced by -sjlog do-.
*
* This subroutine has a 3 line buffer; the end of a log from -sjlog do- will
* always have:
*
* 1. a blank line
* 2. a line with the text: "."
* 3. a line with the text: "end of do-file"
*
* This subroutine also works with smcl files, and TeX files generated from
* smcl files using -log texman- (its original purpose).
*/
program define CleanSJLogDo
args rf wf
/* skip the smcl header lines */
FileRead `rf' line1
if `"${`line1'}"' == "{smcl}" {
/* skip next line too, it is part of the smcl header */
removeLine `line1'
FileRead `rf' line1
removeLine `line1'
}
else {
FileWrite `wf' `line1'
}
FileRead `rf' line1
FileRead `rf' line2
local break 0
while r(eof)==0 {
if substr(`"${`line2'}"',-14,.) == "end of do-file" {
local break 1
continue, break
}
FileWrite `wf' `line1'
local line1 `line2'
FileRead `rf' line2
}
if ! `break' {
FileWrite `wf' `line1'
removeLine `line2'
}
else {
removeLine `line1'
removeLine `line2'
}
end
/* Clean log produced by -sjlog using- and -sjlog close-. */
program define CleanSJLog
args rf wf
CleanLogUsingHeader `rf'
/* skip the smcl header lines */
FileRead `rf' line1
if `"${`line1'}"' == "{smcl}" {
/* skip next line too, it is part of the smcl header */
removeLine `line1'
FileRead `rf' line1
removeLine `line1'
}
else {
FileWrite `wf' `line1'
}
FileRead `rf' line1
FileRead `rf' line2
local break 0
while r(eof)==0 {
if index(`"${`line2'}"',". sjlog close") {
local break 1
continue, break
}
FileWrite `wf' `line1'
local line1 `line2'
FileRead `rf' line2
}
if ! `break' {
FileWrite `wf' `line1'
removeLine `line2'
}
else {
removeLine `line1'
removeLine `line2'
}
end
/* Clean log produced by Stata's -log using- and -log close- commands. */
program define CleanLog
args rf wf
CleanLogUsingHeader `rf'
FileRead `rf' line
local break 0
while r(eof)==0 {
/* stop when we encounter the -log close- command. */
if substr(`"${`line'}"',-11,.) == ". log close" {
local break 1
continue, break
}
FileWrite `wf' `line'
FileRead `rf' line
}
if `break' {
removeLine `line'
}
end
/* Clean log produced by Stata's -log using- command and -logclose-. */
program define CleanLogclose
args rf wf
CleanLogUsingHeader `rf'
FileRead `rf' line
local break 0
while r(eof)==0 {
/* stop when we encounter the -log close- command. */
if substr(`"${`line'}"',-10,.) == ". logclose" {
local break 1
continue, break
}
FileWrite `wf' `line'
FileRead `rf' line
}
if `break' {
removeLine `line'
}
end
/* Skip first 5 lines comprising the header output from -log using-. */
program define CleanLogUsingHeader
args rf
/* hline */
file read `rf' line
if `"`line'"' == "{smcl}" {
file read `rf' line
}
file read `rf' line
if ! index(`"`line'"', "log:") {
file seek `rf' tof
exit
}
file read `rf' line
if ! index(`"`line'"', "log type:") {
file seek `rf' tof
exit
}
file read `rf' line
if ! index(`"`line'"', "opened on:") {
file seek `rf' tof
exit
}
/* blank line */
file read `rf' line
end
/* type: subroutines ********************************************************/
program define LogType
syntax anything(name=file id="filename") [, /*
*/ replace /*
*/ find /*
*/ path(passthru) /*
*/ logfile /*
*/ ]
LogSetup
if "`logfile'" == "" {
local logfile nologfile
}
StripQuotes file , string(`file')
if `"`find'"' != "" {
capture which findfile
if _rc {
di as err "option find requires Stata 8 or later"
exit 111
}
quietly findfile `"`file'"', `path'
local file `r(fn)'
}
LogBaseName `file'
local file `"`r(fn)'"'
local dbase `"`r(dir)'`r(base)'"'
local ext `"`r(ext)'"'
if ! inlist(`"`ext'"',".smcl",".hlp") {
local dbase `"`dbase'`ext'"'
}
capture noisily {
tempfile tt
LogOpen `tt'
type `file'
LogClose, noclean `logfile'
copy `"`tt'.log.tex"' `"`dbase'.log.tex"', `replace'
if "`logfile'" == "logfile" {
copy `"`tt'.log"' `"`dbase'.log"', `replace'
}
}
local rc = _rc
capture erase `"`tt'.smcl"'
capture erase `"`tt'.log.tex"'
exit `rc'
end
exit

View File

@ -0,0 +1,54 @@
program def sortlist, rclass
*! NJC 1.2.0 7 June 2000
* NJC 1.1.0 22 Dec 1999
* NJC 1.0.0 22 Sept 1999
version 6.0
gettoken list 0 : 0, parse(",")
if "`list'" == "" | "`list'" == "," {
di in r "nothing in list"
exit 198
}
syntax [, Noisily Global(str) ]
if length("`global'") > 8 {
di in r "global name must be <=8 characters"
exit 198
}
tokenize `list'
local nwords : word count `list'
if `nwords' > _N {
preserve
clear
qui set obs `nwords'
}
tempvar words miss
qui gen str1 `words' = ""
local i = 1
while `i' <= `nwords' {
local len = length("``i''")
if `len' > 80 {
di in r "cannot handle word length > 80"
exit 498
}
qui replace `words' = "``i''" in `i'
local i = `i' + 1
}
gen byte `miss' = missing(`words')
sort `miss' `words'
local i = 1
while `i' <= `nwords' {
local word = `words'[`i']
local newlist "`newlist' `word'"
local i = `i' + 1
}
if "`noisily'" != "" { di "`newlist'" }
if "`global'" != "" { global `global' "`newlist'" }
return local list `newlist'
end

View File

@ -0,0 +1,2 @@
.h listutil

234
Modules/ado/plus/s/spex.ado Normal file
View File

@ -0,0 +1,234 @@
* spex - version 1.3.1 - fix rologit case2alt bug 25Oct2005
* spex - version 1.3.0 - add asmprobit 08Sep2005
* spex - version 1.2.10 - case2alt modification 11Jul2005
* spex - version 1.2.9 - case2alt 11jul2005
* spex - version 1.2.8 - change directory for spex_data 11Jul2005
* spex - version 1.2.7 - revise misschk 06Jul2005
capture program drop spex
program define spex
** USERS: TO HAVE SPEX SEARCH SOMEWHERE OTHER THAN YOUR WORKING DIRECTORY
** FOR DATA, ENTER THE PATH IN THE QUOTES BELOW (WINDOWS: USE / AS SEPARATOR)
* local userpath "C:/~ToSync/~Projects/stata/spostdata/" // example
local userpath ""
syntax namelist(id="dataset or command") [, Web User Jsl *]
tokenize "`namelist'"
* unabbreviate command
capture _optname , `1'
local cmddta = r(opt)
if "`cmddta'"=="." {
local cmddta = "`1'"
}
local default = "web"
*local default = "jsl"
** SET DIRECTORY WHERE DATA IS STORED
if "`web'" == "web" | ///
("`jsl'"== "" & "`user'" == "" & "`default'" == "web") {
* local where "http://www.stata-press.com/data/lfr/"
local where "http://www.indiana.edu/~jslsoc/stata/spex_data/"
}
if "`user'" == "user" | ///
("`jsl'"== "" & "`web'" == "" & "`default'" == "user") {
local where "`userpath'"
}
if "`jsl'" == "jsl" | ///
("`user'"== "" & "`web'" == "" & "`default'" == "jsl") {
local where "c:\spostdata/"
}
** SPECIFY SYNTAX OF MODEL IF MODEL IS SPECIFIED
if "`cmddta'" == "asmprobit" {
local data travel2
local cmd "asmprobit choice time invc, case(id) alternatives(mode) `options'"
}
if "`cmddta'" == "clogit" {
local data travel2
local cmd "clogit choice train bus time invc, group(id) `options'"
}
if "`cmddta'" == "cloglog" {
local data binlfp2
local cmd "cloglog lfp k5 k618 age wc hc lwg inc, `options'"
}
if "`cmddta'" == "cnreg" {
local data nels_censored2
local cmd "cnreg testscor bymomed bydaded black hispanic, censored(censor) `options'"
}
if "`cmddta'" == "intreg" {
local data nels_censored2
local cmd "intreg minscor maxscor bymomed bydaded black hispanic, `options'"
}
if "`cmddta'" == "logit" {
local data binlfp2
local cmd "logit lfp k5 k618 age wc hc lwg inc, `options'"
}
if "`cmddta'" == "misschk" {
local data gsskidvalue2
*local cmd "misschk year-income91, help"
local cmd ///
"misschk age anykids black degree female kidvalue othrrace year income91 income, help gen(m_) dummy"
}
if "`cmddta'" == "mlogit" {
local data nomocc2
local cmd "mlogit occ white ed exper, `options'"
}
if "`cmddta'" == "mprobit" {
local data nomocc2
local cmd "mprobit occ white ed exper, `options'"
}
if "`cmddta'" == "nbreg" {
local data couart2
local cmd "nbreg art fem mar kid5 phd ment, `options'"
}
if "`cmddta'" == "ologit" {
local data ordwarm2
local cmd "ologit warm yr89 male white age ed prst, `options'"
}
if "`cmddta'" == "oprobit" {
local data ordwarm2
local cmd "oprobit warm yr89 male white age ed prst, `options'"
}
if "`cmddta'" == "poisson" {
local data couart2
local cmd "poisson art fem mar kid5 phd ment, `options'"
}
if "`cmddta'" == "probit" {
local data binlfp2
local cmd "probit lfp k5 k618 age wc hc lwg inc, `options'"
}
if "`cmddta'" == "regress" | "`cmddta'" == "reg" {
local data regjob2
local cmd "regress job fem phd ment fel art cit, `options'"
}
if "`cmddta'" == "rologit" {
local data wlsrnk
local precmd1 `"label variable value1 "est""'
local precmd2 `"label variable value2 "var""'
local precmd3 `"label variable value3 "aut""'
local precmd4 `"label variable value4 "sec""'
local precmd5 "case2alt, yrank(value) case(id) alt(hashi haslo) casevars(fem hn) gen(rank)"
local cmd "rologit rank est* var* aut* hashi haslo, group(id) reverse"
}
if "`cmddta'" == "slogit" {
local data ordwarm2
local cmd "slogit warm yr89 male white age ed prst, `options'"
}
if "`cmddta'" == "tobit" {
local data tobjob2
local cmd "tobit jobcen fem phd ment fel art cit, ll(1)"
}
if "`cmddta'" == "zinb" {
local data couart2
local cmd "zinb art fem mar kid5 phd ment, inf(fem mar kid5 phd ment) `options'"
}
if "`cmddta'" == "zip" {
local data couart2
local cmd "zip art fem mar kid5 phd ment, inf(fem mar kid5 phd ment) `options'"
}
if "`cmddta'" == "ztnb" {
local data couart2
local cmd "ztnb art fem mar kid5 phd ment if art > 0, `options'"
}
if "`cmddta'" == "ztp" {
local data couart2
local cmd "ztp art fem mar kid5 phd ment if art > 0, `options'"
}
if "`cmd'" == "" {
local data "`cmddta'"
}
** LOAD DATAFILE
di _n in white `". use "`where'`data'.dta", clear"'
capture use "`where'`data'", clear
if _rc != 0 {
di _n in green "(trying alternate location for file)"
di _n in white `". sysuse "`data'.dta", clear"'
capture sysuse `data'.dta, clear
if _rc != 0 {
di as err `"program cannot confirm dta file `data' on path `where'"'
error 999
}
}
** EXECUTE COMMAND
* are there commands to be executed before the command?
local i = 1
while `"`precmd`i''"' != "" {
di in white `". `precmd`i''"'
`precmd`i''
local i = `i' + 1
}
if "`cmd'" != "" {
if substr("`cmd'", -2, .) == ", " {
local trim = length("`cmd'") - 2
local cmd = substr("`cmd'", 1, `trim')
}
di _n in white ". `cmd'"
`cmd'
}
end
capture program drop _optname
program define _optname, rclass
version 8
syntax , [BINlfp2 ORDwarm2 REGress LOGit MLOGit OLOGit NOMocc2]
foreach d in binlfp2 ordwarm2 regress logit ///
mlogit ologit nomocc2 {
if "``d''"=="`d'" {
local opt = "`d'"
}
}
return local opt "`opt'"
end

View File

@ -0,0 +1,41 @@
{smcl}
{* 8Jun2005}
{hline}
help for {hi:spex}{right:(part of {hi:spost})}
{hline}
{p 4 4 2}
{title:Load example files and run example models}
{p 4 12 2}{cmd:spex} [{it:modelname}] [{it:filename}] [{cmd:,} {cmdab:w:eb} {cmdab:u:ser}]
{title:Description}
{p 4 4 2}
{cmd:spex} allows users to easily use example files and models from
Long and Freese's {it: Regression Models for Categorical Dependent Variables}
{it: Using Stata}. Typing {cmd:spex} {it:filename} will load the specified
example dataset, while typing {cmd:spex} {it:modelname} will estimate that
model using data and an example specification from the book.
{title:Options}
{p 4 8 2}{cmd:web} indicates that the data are to be accessed from their location
on the spost website (http://www.indiana.edu/~jslsoc/spostdata/). This is
the default.
{p 4 8 2}{cmd:user} indicates that the data are to be accessed from the working directory
or somewhere else along the user's adopath (somewhere accessible
via {cmd:sysuse}).
{title:Notes}
{p 4 4 2}When specifying an estimation command with spex, you can add other
options (e.g., "nolog") and these will be passed along as additional options
to the estimation command.
{title:Authors}
Jeremy Freese and J. Scott Long
www.indiana.edu/~jslsoc/spost.htm
spostsup@indiana.edu

View File

@ -0,0 +1,29 @@
{smcl}
{* 26Jun2006}{...}
{cmd:help spost}
{hline}
{title:SPost commands}
{space 2}{help asprvalue}{col 15}{lalign 25: predictions for alternative specific models}
{space 2}{help brant}{col 15}{lalign 25: Brant test of proportional odds}
{space 2}{help case2alt}{col 15}{lalign 25: 1 obs per row to 1 alternative per row}
{space 2}{help countfit}{col 15}{lalign 25: assess fit in count models}
{space 2}{help fitstat}{col 15}{lalign 25: compute fit statistics}
{space 2}{help leastlikely}{col 15}{lalign 25: find least likely predictions}
{space 2}{help listcoef}{col 15}{lalign 25: list estimated coefficients}
{space 2}{help misschk}{col 15}{lalign 25: examine patterns of missing data}
{space 2}{help mlogplot}{col 15}{lalign 25: plot results from mlogit}
{space 2}{help mlogtest}{col 15}{lalign 25: tests for mlogit}
{space 2}{help mlogview}{col 15}{lalign 25: dialog box for mlogplot}
{space 2}{help praccum}{col 15}{lalign 25: accumulate predictions to plot}
{space 2}{help prchange}{col 15}{lalign 25: compute discrete change coefficients}
{space 2}{help prcounts}{col 15}{lalign 25: compute predictions for count models}
{space 2}{help prgen}{col 15}{lalign 25: create predictions and CIs for plotting}
{space 2}{help prtab}{col 15}{lalign 25: tables of predictions}
{space 2}{help prvalue}{col 15}{lalign 25: predictions with CIs}
{space 2}{help spex}{col 15}{lalign 25: run SPost examples or load SPost data}
{space 2}{help spost_auxillary}{col 15}{lalign 25: help on auxillary commands for SPost}
{hline}

View File

@ -0,0 +1,15 @@
{* 20Oct2009}
{title:Authors}
{p 4 2 0}
If you use SPost, please cite:
{p 4 4 0}
J. Scott Long and Jeremy Freese (2005)
{it:Regression Models for Categorical Outcomes Using Stata. Second Edition.} College Station, TX: Stata Press.
{p 4 2 0}
{browse "http://www.indiana.edu/~jslsoc/web_spost/sp_help.htm":For help, check here.}
{browse "http://www.indiana.edu/~jslsoc/spost.htm":For futher information, see the SPost website.}
{p_end}

View File

@ -0,0 +1,7 @@
// Uninstall and re-install spost9_ado
program define spostupdate
capture ado uninstall spost9_ado
net from http://www.indiana.edu/~jslsoc/stata/
net install spost9_ado
end

View File

@ -0,0 +1,44 @@
program def sublist, rclass
*! NJC 1.3.0 7 June 2000
* NJC 1.2.0 31 Jan 2000
* NJC 1.1.0 22 Dec 1999
* NJC 1.0.0 12 November 1999
version 6.0
gettoken list 0 : 0, parse(",")
if "`list'" == "" | "`list'" == "," {
di in r "nothing in list"
exit 198
}
syntax , From(str) [ To(str) ALL Noisily Global(str)]
if length("`global'") > 8 {
di in r "global name must be <=8 characters"
exit 198
}
tokenize `list'
local nwords : word count `list'
local i = 1
while `i' <= `nwords' {
local len = length("``i''")
if `len' > 80 {
di in r "cannot handle word length > 80"
exit 498
}
local i = `i' + 1
}
while "`1'" != "" {
if index("`1'", "`from'") {
local 1 : subinstr local 1 "`from'" "`to'", `all'
}
local newlist "`newlist'`1' "
mac shift
}
if "`noisily'" != "" { di "`newlist'" }
if "`global'" != "" { global `global' "`newlist'" }
return local list `newlist'
end

View File

@ -0,0 +1,2 @@
.h listutil

View File

@ -0,0 +1,36 @@
program def sumlist, rclass
*! NJC 1.0.0 9 April 2001
version 6.0
gettoken list 0 : 0, parse(",")
if "`list'" == "" | "`list'" == "," {
di in r "no list specified"
exit 198
}
numlist "`list'"
local list `r(numlist)'
local nw : word count `list'
syntax [ , Global(str) Noisily ]
if length("`global'") > 8 {
di in r "global name must be <=8 characters"
exit 198
}
tempname sum
scalar `sum' = 0
tokenize `list'
local i = 1
while `i' <= `nw' {
scalar `sum' = (`sum') + (``i'')
local i = `i' + 1
}
if "`noisily'" != "" { di `sum' }
if "`global'" != "" { global `global' = `sum' }
return scalar sum = `sum'
end

View File

@ -0,0 +1,2 @@
.h listutil