text stringlengths 0 538k |
|---|
*! version 1.0.1 27Sep2016
*! version 1.0.2 05Jun2017 major changes in the code and how the whole routine works, added exponential and parameters options
*! authors: Gabriele Rovigatti, University of Chicago Booth, Chicago, IL & EIEF, Rome, Italy. mailto: gabriele.rovigatti@gmail.com
*! Vincenzo Mollisi, Bolza... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
04-Jan-2019
10. Read_Token_From_File.do
Do not save API tokens in scripts that may get seen by others.
Your script should read in your token from a private location.
*/
version 12
set more off
clear
* specify a text file ... |
/*******************************************************************************
Download a dataset using the REDCap API
Download metadata for the variables and apply labels etc.
Note the following field types cannot have their values labelled because the label information is not incuded in the data dictionary:
- redc... |
/*******************************************************************************
Example of API File Export and Import
Luke Stevens
22-Jan-2021
*******************************************************************************/
version 16
clear
set more off
import delimited tokens.txt
local apisource=url in 1
local api... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
1. Simple_Export.do
A basic API call to download all data from your REDCap project to a CSV file.
*/
version 12
set more off
clear
local token "<insert your token here>"
local outfile "exported_data.csv"
shell c... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
2. Export_Fields_Instruments.do
Specify specific fields and instruments to download.
--form fields=varname // include varname in downloaded dataset
--form fields[]=varname1 // include varname1 ...
--fo... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
3. Export_Filter.do
Specify an expression that will filter the records downloaded.
--form filterLogic="<expr>" // expression in REDCap syntax
*/
version 12
set more off
clear
local token "<insert your token... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
4. Export_Report.do
Specify a REDCap report to download.
--form content=report
--form report_id=<id> // numeric report id from right-hand column of report list
--form longitudinal_reports=1 // can be u... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
5. Export_Metadata.do
Illustrating metadata (data dictionary) download - not just records.
--form fields=varname // download varname metadata (only)
--form fields[]=varname1 // download varname1 ...
--f... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
6. Import_Records.do
Illustrating data import - API is not just for export.
(This example toggles the gender of first record 1 <-> 2)
Ensure that you (your role) has "API Import" permission.
*/
version 12
se... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
7. Build_Command_String.do
An example of building the curl command programmatically.
- Timestamp in downloaded file name
- Iterate a supplied list of fields
- Iterate a supplied list of evnts
- Iterate a ... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
20-Jun-2017
8. Debugging.do
How to troubleshoot your do-file and API calls:
- Badly formed curl command -> display and copy to command prompt
- API returns error -> review contents of outfile
*/
version 12
set mor... |
/**
Using the REDCap API with Stata
Luke Stevens, Murdoch Childrens Research Institute
10-Apr-2018
9. Delete_Records.do
An example of deleting multiple records.
Nb. The user must have the "Delete Records" permission enabled.
*/
version 12
set more off
clear
local curlpath="c:\curl\curl.exe"
local apiurl="htt... |
*! version 1.1
*! helpful if you want to put variable names in matrix row/colnames
program abbrev_all
version 11.0 //just a guess here
syntax , str_list(string asis) out_loc(string) [length(int 32)]
forval i=1/`:word count `str_list''{
local part = abbrev("`: word `i' of `str_list''",`length')
if `i'==1 loca... |
*! v1.0 Brian Quistorff <bquistorff@gmail.com>
*! Adds a fake variable. Useful for adding new rows to a table using esttab/estout
*Requires: Needs erepost
program add_fake_coeff_to_e, eclass
version 11.0
*Just a guess at the version
args cname cval
tempname eb eb2 eV eV2
mat `eb' = e(b)
local eb_names : colna... |
*! version 1.1.1 13feb2015 - use net_install to allow relative local paths. Brian Quistorff <bquistorff@gmail.com>
*! version 1.1.0 09jun2011
program adoupdate, rclass
version 9
syntax [anything(name=pkglist id="package list")] [, ///
ALL ///
DIR(string) ///
SSConly ///
UPDATE ///
VERBOSE ///
... |
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Simplifies quick asserts
program assert_count
version 11.0
*Just a guess at the version
syntax [if], rn(string) [message(string)]
qui count `if'
assert_msg `r(N)'`rn', message(`message')
end
|
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! An assert with a message when false
*! Similar to -_assert- except have a pause
program assert_msg
version 11.0
*Just a guess at the version
syntax anything [, message(string)]
cap assert `anything', fast
if _rc==1 { //Break key
error 1
}
if _rc!=0 {... |
*! version 1.2 Brian Quistorff <bquistorff@gmail.com>
program assign_treatment
version 11.0 //Just a guess
syntax varlist, generate(namelist max=1) num_treatments(int) [handle_misfit(string)]
if "`handle_misfit'"=="" local handle_misfit = "obalance"
* Error checking
_assert inlist("`handle_misfit'","obalance","... |
*! version 1.1 Brian Quistorff April 2015
*! version 1.0.11 (chardel) by NJC 1.0.1 1 April 2000
*! Blanks out all chars for everything in the namelist passed in.
*! Along with reshape, destring also sometimes adds a var[destring] char
program def bchardel
version 10.0
syntax namelist
foreach name in `namelist'{... |
*! version 1.0
program bcount
version 11 //guess
syntax [if] [in], local(string)
count `if' `in'
c_local `local' `r(N)'
end
|
*! v0.1 Brian Quistorff <bquistorff@gmail.com>
*! allows things like -drop emp*, except(emp)-
program bdrop
version 11
syntax varlist [, except(string)]
unab varlist_full : `varlist'
local to_drop : list varlist_full - except
drop `to_drop'
end
|
*! v0.1 Brian Quistorff <bquistorff@gmail.com>
*! A merge pass-through function with additions:
*! 1) Allows merging when key variables are named differently. (using_match_vars())
*! 2) Shows the full match stats (even when using keep())
*! 3) Maintains sort (using ", stable")
*! 4) return in r() the tab of _merge
prog... |
*! Given a set of predictors, and treatment time:
*! -drops units without complete info
*! -will limit sample size if testing
*! -GE:
*! --will identify donors via GE concerns
*! --will compare predicttion errors with and without GE containated removed
*! -Main estimation (including placebo units)
*! -will chec... |
*! Builds the matrices needed by the graphing programs
*! Works if the unit is one of the donors a permuation estimation was done on.
program build_graphing_mats, rclass
version 11.0 //just a guess here
syntax anything, depvar(string) startper(int) perms_file(string)
qui tsset, noquery
local pvar = "`r(panelvar)'... |
*! version 0.1
*! Brian Quistorff
*! Usage:
*! change_line using table.tex, ln(10) insert("blah")
*! change_line using table.tex, ln(10) delete
*! change_line using table.tex, ln(10) replace("blah")
program change_line
version 11 //a guess
syntax using/, ln(int) [insert(string) delete replace(string)]
tempfile new... |
*! Purpose: Right now just check if inside the upper-/lower-envelope
*! Also graphs the raw data a bit
* To do: maybe eventually use the Gary King program
program check_in_convex_hull
version 11.0 //just a guess here
syntax varname, first_pre(int) last_pre(int) trunit(int) file_suff(string) ///
[gph_tvar(string) m... |
*! v0.3 Brian Quistorff <bquistorff@gmail.com>
*! Clears more than -clear all-.
*! It can't clear the locals from the calling context, so still might want to -mac drop _all-
*! (but unnecessary if used at top of do file that is only run (no -include-d) as it will have its own local context anyways)
program clear_all
v... |
*! version 1.0 Brian Quistorff
* Reshape leaves a bunch of cars around so that it can be undone.
* in interactive mode this is nice, but otherwise they are messy.
program clear_reshape_chars
version 11.0 //just a guess here
char _dta[ReS_str]
char _dta[ReS_j]
char _dta[ReS_ver]
char _dta[ReS_i]
char _dta[ReS_Xij... |
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Closes all files that were open in mata
*! -clear all- doesn't close mata open files!
* From http://www.stata.com/statalist/archive/2006-10/msg00794.html
program closeallmatafiles
version 9
forvalues i=0(1)50 {
capture mata: fclose(`i')
}
end
|
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! This will collapse the dataset and preserve the variable and value labels.
*! The syntax for using this is just like with the collapse command.
*! There is one additional optional option: show stat. If you add this option to the command (collapseandperserve ... ... |
*! Compares the prediction errors from the normal setup with a placebo test one period before
program compare_pred_errors
version 11.0 //just a guess here
syntax , depvar(string) tr_unit_codes(string) file_suff(string) perms(int) ge_suff(string) ///
early_predictors(string) late_predictors(string) precise_tyear(int... |
*! Makes sure
*! Marks obs with which are complete
*! Can handle normal variables and time subscripted variables (e.g. pop(1980))
program complete_units
version 11.0 //just a guess here
syntax anything, generate(string)
cap tsset, noquery
if _rc==0 {
local pvar = "`r(panelvar)'"
local tvar = "`r(timevar)'"
... |
*! version 0.1 Brian Quistorff
*! Cross-fitting a model to product honest predictions/residuals and fit statistics:
*! crossfit newvar [, k(int 5) by(varname) residuals outcome(varname) nodots] : est_cmd
*! est_cmd needs to fit the basic "syntax" format (we sneak in a new 'if' clause)
*! Simple usage: crossfit price_... |
*! version 1.1
*! For numerical replication need to list operating system, application version, and processor type
*! Essentially a different take on -about- (but I don't care about memory, license, copyright)
* Ref: http://www.stata.com/support/faqs/windows/results-in-different-versions/
* Note that log open/close tim... |
*! v0.3
*! like -drop if- but appends the if condition to the # dropped msg
*! Helpful if used inside a loop or program where you wouldn't see the command echoed.
program drop_if, rclass
version 10
*version is a guess
syntax anything(equalok everything)
qui count if `anything'
local num=r(N)
qui drop if `anything... |
*! v0.3 Brian Quistorff <bquistorff@gmail.com>
*! Shows the version of the Stata dataset whose filename is passed in.
program ds_version, rclass
version 11.0 //just a guess here
args fname
tempname fhandle v
file open `fhandle' using `fname', read binary
file read `fhandle' %1s firstbytechar
if "`firstbytechar'"... |
*! version 1.2 Brian Quistorff <bquistorff@gmail.com>
*! Passthrough command allowing one to use the -ereturn- cmds easily.
* Usage: ereturn_do local l1 yes
* Usage: ereturn_do matrix y = y, copy
/* Notes for "post": 1) you need colnames(V)=rownames(V)=colnames(b)
2) the supplied matrices are moved, not copied
*E... |
*! version 1.1 Brian Quistorff <bquistorff@gmail.com>
*! Escapes Latex meta-chatacters
*! Watch the backslashes as Stata is a bit uncommon in how it deals with them.
*! For the caret, it requires the textcomp package
* http://stackoverflow.com/questions/2627135/how-do-i-sanitize-latex-input
mata:
/*
* Do simultaneous... |
program escape_latex_file
version 11 //just a guess
syntax, txt_infile(string) tex_outfile(string)
tempname out_handle in_handle
file open `out_handle' using "`tex_outfile'", write text replace
file open `in_handle' using "`txt_infile'" , read text
file read `in_handle' line
while r(eof)==0 {
escape_latex "`... |
*! eval_synth_model: For given predictors, treatment time, donors, treated units, and placebo units.
*! Computes the model, does RI, produces graphs & tables, converts to delta_t=1
*
*Required globals: dir_base
* Needs the data to be in a strongly balanced panel
program eval_synth_model, rclass
version ... |
*Version 0.1 Brian Quistorff <bquistorff@gmail.com>
* Description: Returns the first line that matches the regular expression (or 0)
program find_in_file
version 12 //guess
syntax using/, regexp(string) local(string) [start_at_ln(int 0)]
tempname fh
local linenum = 0
local line_on = 0
file open `fh' using `"`us... |
*Version 0.1 Brian Quistorff <bquistorff@gmail.com>
* Description: Similar to sample but for data in file (so big datasets).
program define fsample
version 11.0 //Just a guess at the version
args f gsize ssize
qui describe using "`f'", short
local fsize r(N)
local ncompletegroups `=floor(`fsize'/`gsize')'
temp... |
*! gen_perm_donors: Runs permutation estimations on donors
*! Needs dataset to be with delta_t=1 and with only donors
*
* Required globals: fargs, dir_base
* Suboptions: fargs = predictors(string)
program gen_perm_donors
version 11.0 //just a guess here
syntax , donor_mat(string) depvar(string) infile(string) ///
... |
*! version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Generates a unique id for each pair (like egen ... group())
*! but makes sure they don't have leading 0s
program gen_robust_id
version 11.0
*Just a guess at the version
syntax varlist, generate(string)
tempvar tv
egen `tv' = group(`varlist')
summ `tv', ... |
*! v1.3 Brian Quistorff <bquistorff@gmail.com>
*! If you like to store your config values in a csv file
*! (with headers "key" and "value") then this can retrieve those
*! Will default to local of the name `key'
*! if testing=1 will check for key-testing first
*! binding quotes will be removed (Stata style)
*! if you w... |
*! version 1.0
*! Retrieves the key
program get_key, sclass
version 11 //guess
loc key : char _dta[key]
di "key: `key'"
sreturn local key "`key'"
end
|
* will store into locals the return values from command (some commands should 1-liners!)
* Ex:
* get_returns pvar=r(panelvar) tvar=r(timevar) : tsset, noquery
program get_returns
gettoken my_opts 0: 0, parse(":")
gettoken colon their_cmd: 0, parse(":")
`their_cmd'
foreach my_opt in `my_opts'{
if regexm("`my_o... |
*! v1.1 bquistorff@gmail.com
*! converts a *.gph file to three possible derivative files
program gph2fmt
version 12.0 //just a guess
syntax anything(everything name=gph_file), [plain_file(string) titleless_file(string) bare_file(string)]
tempname toexport
graph use `gph_file', name(`toexport')
if "`plain_file'... |
*! Graphs the prediction errors
*! Required globals: dir_base
program graph_PEs
version 11.0 //just a guess here
syntax , start(int) file_suff(string) title(string) notes(string) ///
tper_spec(int) y_diff(string) y_diffs(string) ///
[ytitle(string) tval_labels(string) xlabels(string) main_label(string)]
tempna... |
*! Graphs the treatment and control
*! Required globals: dir_base
* To do: Need to convert the xlab code to like it is in graph_tc_ci
program graph_tc
version 11.0 //just a guess here
syntax , start(int) file_suff(string) title(string) notes(string) ///
tper_spec(int) ytitle(string) tc_outcome(string) ///
[tv... |
*! Graphs Treatment and Control with Confidence Intervals
*! Required globals: dir_base
program graph_tc_ci
version 11.0 //just a guess here
syntax , file_suff(string) title(string) ///
tper_spec(int) num_reps(int) tc_outcome(string) cis(string) ///
[start(int 1) ci_num(string) tval_labels(string) tc_gph_opts(... |
*! Identifies uncontaminated donors with a temporal placebo test
program identify_donors_placebo
version 11.0 //just a guess here
syntax , depvar(varname) predictors(string) tr_unit_codes(numlist integer) ///
early_predictors(string) precise_tyear(int) last_pre_year(int) tper(int) ///
file_suff(string) perms(int)... |
*! v0.2 Brian Quistorff <bquistorff@gmail.com>
*! A replacement for -tempfile- that provides more options for non-local outputs
*! 1) Creates auto-named globally-scoped files in tmpdir (ie persistent files the user is in charge of deleting)
*! 2) Can assign the file names to global macros
* Main usage: a script that us... |
*! version 0.1 Brian Quistorff <bquistorff@gmail.com>
* Description: Generates strings corresponding to
* ISO 8601 data and date-time formats. These may
* be useful for generating log-file filenames.
* Returns:
* s(iso8601_d) : 2000-12-25
* s(iso8601_dt) : 2000-12-25T13:01:01
* s(iso8601_dt_file): 2... |
*! v0.2 Brian Quistorff <bquistorff@gmail.com>
*! reports if the string is a
program is_abs_path, rclass
version 11.0 //just a guess here
syntax anything(everything name=place), local(string)
tempname `is_abs_path'
scalar `is_abs_path' = substr("`place'",1,5)!="http:" | substr("`place'",1,6)!="https:" | substr("`p... |
*! ivreg2out 1.0
*BQ: 2013-09-24 removed the N_Unique ereturn
* (had a problem with my setup. I think my est's didn't have e(r))
* Combines the two stage estimates into a single estimate
* Originally from roywada@hotmail.com http://www.stata.com/statalist/archive/2009-09/msg00043.html
prog define ivreg2out, eclass
ve... |
*! 1.2 Brian Quistorff <bquistorff@gmail.com>
* 26-09-2013 modification of -latabstat- (see SSC) to remove the Source footnote and make a smaller tex fragment.
program define latabstat_simple, rclass byable(recall) sort
version 6
syntax varlist(numeric) [if] [in] [aw fw] [ , /*
*/ BY(varname) CASEwise Columns(str)... |
*! version 0.1 Brian Quistorff
*! in the anything part puts line1\\line2
*There are several ways
*1) Using packages
*1a) \usepackage{makecell}
*1b) \usepackage{pbox} (have to specifying a max width) (better than parbox)
*1c) minipage (have to specifying a width)
*1d) shortstack
* 2) Plain Latex
* 2a) insert a 1 column ... |
*! version 1.0 Brian Quistorff bquistorff@gmail.com
*! Makes a multiline label for a variable to be used in a tex table.
*! Usage: latex_multiline_var_label , lines("line 1" "line 2")
program latex_multiline_var_label
version 10.0 //guess
syntax , lines(string asis) [local(string) var2label(string) noindent nomultir... |
*! version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Creates axis ticks (major & minor) for log scales
*! (Stata's auto ticks are bad)
program log_axis_ticks, sclass
version 11.0
*Just a guess at the version
syntax , [range(numlist) vars(varlist numeric) label_scale(string)]
* Get the range
if "`range'"!="... |
*! version 0.1
*! Will put commas in between words in a list (so can be used in foreach loop)
*! This uses a word=based matching which works if the words are quoted string
*! (where a simple " "->"," won't work)
program make_for_inlist
version 11.0
*Just a guess at the version
syntax anything(everything), local(s... |
*! Version 1.2
*! Originally from: version 1.1.9 02feb2005 by Marc-Andreas Muendler: muendler@ucsd.edu
program define matload_simple
version 11.0 //just a guess here
syntax anything [, Path(string) ROWname(string) OVERwrite]
global err_mssg = ""
local rc 0
local matname= subinstr("`anything'",",","",1)
local ... |
*! version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Sorts a Stata matrix by a column. Fixes problem in -matsort- where row labels with spaces are mangled
*! make sortcol negative if you want descending order
program matrixsort
version 11.0
*Just a guess at the version
args matname sortcol
mata: sort_st_mat... |
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Creates the post init and post string lines that will come from a matrix
program matrix_post_lines, sclass
version 12
syntax , matrix(string) varstub(string) varnumend(int) [varnumstart(int 1)]
*Create the post strings (faster in mata and nicer in traced-log... |
*! Version 1.2 Brian Quistorff
*! Originally from: version 1.1.7 24oct2004 by Marc-Andreas Muendler: muendler@ucsd.edu
*! BQ: Make saving automatic (no dropall), remove manual -more-s,
*! put the full filename in path (not just dir) so can save to a name that is not the matrix name
*! Requires save12
program define... |
*! v0.1 Brian Quistorff <bquistorff@gmail.com>
*! pass-through for -net describe- that allows local relative path
program net_describe
version 11.0 //just a guess here
syntax namelist(name=pkgname max=1) [, from(string)]
is_abs_path "`from'"
if r(is_abs_path) {
local from `"`c(pwd)'/`from'"'
}
net describe `pkg... |
*! v0.1 Brian Quistorff <bquistorff@gmail.com>
*! pass-through for -net from- that allows local relative path
program net_from
version 11.0 //just a guess here
args place
is_abs_path "`place'"
if r(is_abs_path) {
local place `"`c(pwd)'/`place'"'
}
net from `place'
end
|
*! v0.1 Brian Quistorff <bquistorff@gmail.com>
*! pass-through for -net get- that allows local relative path
program net_get
version 11.0 //just a guess here
syntax namelist(name=pkgname max=1) [, all replace force from(string)]
is_abs_path "`from'"
if r(is_abs_path) {
local from `"`c(pwd)'/`from'"'
}
net get `... |
*! v0.1 Brian Quistorff <bquistorff@gmail.com>
*! pass-through for -net install- that allows local relative path
program net_install
version 11.0 //just a guess here
syntax namelist(name=pkgname max=1) [, all replace force from(string)]
is_abs_path "`from'", local(iap)
if `iap' {
local from `"`c(pwd)'/`from'"'
... |
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Replaces -profiler report- and create a dta as output (rather than a text file)
*! Requires: save_cmd_output.ado
program nice_profile_report
version 12
syntax , outfile(string)
tempfile textoutput
save_cmd_output, outfile("`textoutput'") command(profiler rep... |
*! Output (in dta and tex formats) a matrix of some quality of the predictors
* Required globals: dir_base
program output_pred_mat
version 11.0 //just a guess here
syntax , file_suff(string) mat(string) mattype(string) [year_replace_period_list(string) nosort]
*Output to a dta file
tempname matw
mat `matw' = `ma... |
*! Outputs a tex p-value table
program output_pval_table
version 11.0 //just a guess here
syntax , note(string) file_base(string) matrix(string)
local orig_linesize = "`c(linesize)'"
set linesize 160
frmttable using "${dir_base}/tab/tex/`file_base'_temp.tex", ///
replace statmat(`matrix') tex fragment note("`n... |
*! Outputs matrix (in dta and tex) of unit level matches
*! Requires globals: dir_base
program output_unit_matches
version 11.0 //just a guess here
syntax , numb(int) file_suff(string) weights_unr(string) weights(string) [match_file(string)]
tempfile initdata
qui save `initdata'
qui drop _all
qui svmat `weights... |
*! v1.0.8 Brian Quistorff <bquistorff@gmail.com>
*! A modified version of -outtable- v1.0.7 (see SSC) to remove the outer \table output so that it can be included in LyX
program define outtable_simple,rclass
version 8.0
syntax using/, mat(string) [Replace APPend noBOX Center ASIS CAPtion(string) Format(string) noROWlab... |
*! cleans up from old parallel and sets the number of clusters (has default for automatic #)
*! Globals required: numclusters
program parallel_clean_setclusters
version 11.0 //just a guess here
syntax [anything] [, noclean]
if "`anything'"==""{
if "${doparallel}"!="1" | "${numclusters}"=="1"{
global numcluster... |
*! Does: parses up uneven tasks, takes care of the seed, appends datasets, cleans up temps
*! Assumed globals: numclusters, dir_base
*! If doesn't work do:
*! parallel clean, all force
*! Right now if something goes wrong, tempfiles are left around in temp folder (slightly bad).
program parallel_justout_helper
versio... |
*! v1.0 Brian Quistorff <bquistorff@gmail.com>
*! Post your own matrices to e(b) and e(V)
prog define post_eb_eV, eclass
version 8.0
args beta vari
eret post `beta' `vari'
eret loc cmd="post_eb_eV"
end
|
*! Version 1.1
*! A variant of _dots (simple progress bar) with time estimates
*! If you don't want to keep track of curr (e.g. in a foreach loop)
*! Then just pass in one parameter being the end.
/* To make deterministic output
s/^After .+/-normalized-/g
s/^(\.[^0-9]*)[0-9]+(s elapsed\.)/\1-normalized-\2/g
*/
program ... |
*! version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Stata bindings for R's ranger package for random forest. Fits and generate predictions (either in standard or out-of-bag)
*! ranger varlist(fv) [if] [pw/], [predict(string) predict_oob(string) num_trees(int 500)]
* predict_oob will do out-of-bag for estimation... |
*! version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! clearing will reset all macros but S_ADO (adopath)
program reset_ADO
version 12
global S_ADO `"BASE;SITE;.;PERSONAL;PLUS;OLDPLACE"'
end
|
*! version 1.1 Brian Quistorff <bquistorff@gmail.com>
*! A simple way to advance the Stata RNG state by a fixed amount
*! Will also fill a variable with a sequence of such states
*! (first obs gets current state, user capture state after function for continuing).
program rng_advance
version 12
syntax anything [, var(... |
program run_pywin32_hidden
* Deal with weirdness where if cmd sees something with
loc 0 = strtrim(`"`0'"')
loc 0_len = strlen(`"`0'"')
loc 0_rest = substr(`"`0'"', 9, `=`0_len'-9')
if substr(`"`0'"', 1, 8)==`"cmd /c ""' & substr(`"`0'"', `0_len', 1)==`"""' & strpos(`"`0_rest'"',`"""')>0 {
lo... |
*! version 0.0.8 Brian Quistorff <bquistorff@gmail.com>
*! Can try to save in either dataset version 114 or 115 which
*! is readable by Stata v11-13
* version map: Stata (dataset): v11 (114) v12(115) v13 (117) v14 (118).
* Stata can always read earlier dataset formats. Additionally, v11
* can read v115 datasets as the ... |
*! version 0.1 Brian Quistorff <bquistorff@gmail.com>
*! converts a file using save12. Can prefix a command (that produces it).
program save12_convert
if regexm(`"`0'"',":") {
gettoken 0 colon_command : 0, parse(":")
gettoken colon command : colon_command, parse(":")
`command'
}
syntax anything [, replace *]
... |
*! version 0.0.1 Brian Quistorff <bquistorff@gmail.com>
*! Some helper utilities when saving so that common saving tasks can be on one line
*! Also warns if saving tempvars. Be careful with these. If you open a dta file with
*! tempvars and Stata's internal temp counter is different (e.g. open in a fresh session) there... |
*! Version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Saves the output form a shell command
*TODO: Anyway to fix-up line wrapping?
program save_cmd_output
version 12
syntax, outfile(string) command(string)
*First get the raw log output
*Set linesize to max so little wrapping
local orig_linesize = `c(linesi... |
*! v1.1 bquistorff@gmail.com
*! saving text versions of title & notes (including wrapping for gph output) as well as the gph_file.
program save_fig
version 12.0 //just a guess
*Strip off and deal with my suboptions
gettoken 0 remainder : 0, parse(":")
syntax , gph_file(string) [title_file(string) caption_file(strin... |
*! v1.2 Brian Quistorff <bquistorff@gmail.com>
*! Does tasks you normally want to do when you establish a key
program set_key
version 11 //guess
syntax varlist [, sort order xtset tsset]
isid `varlist'
char _dta[key] `varlist'
if "`xtset'"!="" xtset `varlist'
if "`tsset'"!="" tsset `varlist'
if "`sort'"!... |
*! Version 1.2 Brian Quistorff <bquistorff@gmail.com>
*! Latex output of summary stats
**************************************
*Editted slightly by Brian Quistorff 11-09-2013
* -allows filenames with spaces
* -allows dropping the \begin{table} \end{table} lines (better for customization)
*This is sutex.ado beta version
... |
*! version 0.0.7 Jens Hainmueller 01/26/2014
*! version 0.0.7-bq Brian Quistorff 2014-02
* -output the unrounded weights plus some other convenience vars.
* -Don't leave mats lying around
* -make a bit faster by speeding up averaging, removing some checks, and not calling tsset redudantly
* -allow for spread ... |
/* subroutine lossfunction: loss function for nested optimization */
program synth2_ll
version 9.2
args todo b lnf
tempname loss bb VV H c A l u wsol
tempvar loss_var loss_final
*matrix list `b'
/* get abs constrained weights and create V */
mata: getabs("`b'")
mat `bb' = matout
mat `VV' = diag(`bb')
/* Set... |
*GE_mode
global GE_mode_nothing 0
global GE_mode_custom_cmd 1
global GE_mode_trim_early_placebo 2
*Drop reason
global Synth_PE_high 2
global Synth_PE_low 3
global Synth_opt_error 4
*Unit types
global Unit_type_treated 1
global Unit_type_donor 2
label define unit_type ${Unit_type_treated} "Treated" ${Unit_type_donor}... |
* Builds an mlib from mata files
* Call this with a single argument that is a list (wrap all in double quotes).
* The first element is mlib the rest are the mata files.
* (Has to be one list otherwise when calling -$STATABATCH do cli_build_mlib.do l/lp.mlib a/a.mata-
* the logfile will be a.log rather than cli_build_m... |
sysdir set PERSONAL "."
sysdir set PLUS "." //some commands think this has to be in S_ADO
global S_ADO "PERSONAL;BASE"
net set ado PERSONAL
mata: mata mlib index
|
*! version 1.1.0 05oct1999 Jeroen Weesie/ICS (STB-53: dm75) (modfied)
*http://www.stata.com/statalist/archive/2007-03/msg00584.html
program define tabl
version 6.0
syntax varlist [if ] [in] [, Width(int 40)]
tokenize `varlist'
while "`1'" != "" {
Tabl `1' `if' `in', width(`width')
mac shift
}
end
/* Tab... |
*! version 1.0 Brian Quistorff <bquistorff@gmail.com>
*! Makes compressed scales (like log scales) when both positive and negative numbers exist.
*! It makes a linear patch in the middle.
*! Usage:
*! trilog , source(orig_var) generate(new_var)
*! trilog , labels(-100 -10 -1 0 1 10 100)
*! local new_labels `"`r(ret... |
log using "net_test.log", replace
local dirs :dir .. dirs ?
foreach dir in `dirs'{
local pkgs : dir "../`dir'/" files "*.pkg"
foreach pkg in `pkgs'{
local pkg_name = substr("`pkg'",1, length("`pkg'")-4)
net describe `pkg_name', from (https://raw.github.com/bquistorff/Stata-modules/master/`dir'/)
}
}
log close
|
set PLUS "`c(pwd)'/../"
set PERSONAL "`c(pwd)'/../"
log using testall.log, name(testall) replace
local dirs :dir . dir *
foreach dir in `dirs'{
cd `dir'
do `test.do
cd ..
}
do net_tests.do
log close testall
|
*Returns the maximum difference of the count of cells in each treatment group
* can omit cell_var (first arg will then be treat_var)
program cell_count_diff_per_t, rclass
args cell_var treat_var
if "`treat_var'"==""{
local treat_var = "`cell_var'"
tempvar cell_var
gen byte `cell_var' = 1
}
summ `cell_var'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.