-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathestdocx.ado
1555 lines (1238 loc) · 54.2 KB
/
estdocx.ado
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**************************************************************************/
/**TODO **/
/**************************************************************************/
// * free-parameters:
// Program does not handle multiple equation models such as'
// xtlogit with ancilliary/free paramters that should not be transformed. Program needs to honor the
// equation name where free paramters have a different equation name, In r(table) all params
// after / in the equation name are free paramters "Free parameters are scalar parameters,
// variances, covariances, and the like that are part of the model being fit"
//
// These should be handled differntly removed from the matrix of parameters and placed
// in the stats matrix and handled separatly printed under each model. Currenlty free paramters
// are reported in eform wich is an error.
//
//
// * BUG:if a variable has no valuelables program ends in Error st_vlmap(): 3300 argument out of range
//
// * BUG: if factor has more than single digit level program throws error
//
// * BUG: Omitted variables are incorrectly displayed as (base)
//
// * Implement additonal signs for significanse with dagger mark as e.g. style
// in Demography.
//
// * *Indicate stratified variables in cox-regressions
//
// * Implement a possibility to include a note below the regression table e.g. source comment etc.
/*###############################################################################################*/
/**SUB-ROUTINES **/
/*###############################################################################################*/
/*########################################################################*/
program check_stats
version 17
syntax anything(name=statlist id="Statistics"), allowed(string)
foreach stat in `statlist' {
// get postion of stat in list of allowed statistics
local i : list posof "`stat'" in allowed
if(!`i') {
di _newline(3)
di as error "ERROR: `stat' is not an allowed statistic in option stats()"
di _newline
error 197
}
}
end
/*########################################################################*/
program create_docx
version 17
syntax , pagesize(string) [landscape]
/**************************************************************************/
/** CREATE THE WORDDOCUMENT THAT WILL HOLD THE TABLE **/
/**************************************************************************/
// clear any unsaved documents from memory
putdocx clear
if "`landscape'"!="" putdocx begin, pagesize(`pagesize') landscape
else putdocx begin, pagesize(`pagesize')
end
/*########################################################################*/
program create_table
version 17
syntax namelist(name=models), pagesize(string) [title(string)] [landscape]
/**************************************************************************/
/** SET WIDTH OF THE TABLE **/
/**************************************************************************/
local nummodels :list sizeof models
// set the width of the table= nummodels + one rowheader column to display variable
// names and factor levels in case var is a factor
local COLUMNS= `nummodels' +1
// check tht there is an active document in memory
capture putdocx describe
if _rc!=0 {
display as error "No active document in memory. "
display as error "If you are using the option inline "
display as error "you first have to run the command putdocx begin "
display as error "before calling estdocx"
exit _rc
}
//print title of table it there is one
if ("`title'"!="") {
// try insering title, will throw error if there is no active paragraph
capture putdocx text ("`title'"), bold
if _rc!=0 {
putdocx paragraph, halign(left) spacing(after, 0)
putdocx text ("`title'"), bold
}
}
/**************************************************************************/
/** CREATE THE HEADER ROW TABLE USING `ROWS',`COLUMNS' DIMENSIONS **/
/**************************************************************************/
putdocx table esttable = (1,`COLUMNS'), ///
border(start, nil) ///
border(insideH, nil) ///
border(insideV, nil) ///
border(end, nil) ///
halign(left) layout(autofitcontents)
//set column lable for x-variables
putdocx table esttable(1,1) = ("Variables"), bold font(Garamond, 11) halign(left)
forvalues col=2/`COLUMNS' {
local mod= `col'-1
local model: word `mod' of `models'
putdocx table esttable(1,`col') = ("`model'"), bold font(Garamond, 11) halign(left)
}
end
/*########################################################################*/
program set_headers
version 17
syntax , headers(string asis) nummod(integer)
//di `"headers: `headers'"'
// get first col to be able to start the loop
gettoken col headers : headers, parse(`"" "')
while(`"`col'"' != "") {
confirm integer number `col'
//di `"col: `col'"'
// confirm that specified col is in te range ofnumod
if (`col' < 1 | `col' > `nummod') {
di as error "The value: `col' set in option headers() is invalid; column out of range"
error 125
exit _rc
}
local col= `col'+1
gettoken heading headers : headers, parse(`"" "')
//di `"heading: `heading'"'
// write heading to table
putdocx table esttable(1,`col') = ("`heading'"), bold font(Garamond, 11) halign(left)
// get next col
gettoken col headers : headers, parse(`"" "')
}
end
/*########################################################################*/
program write_legend
version 15.1
syntax, star(string) row(integer) col(integer)
local sigs: word count `star'
local text "legend: "
forvalues sig=1/`sigs' {
local p: word `sig' of `star' //.05
local s= "`s'*"
local text= "`text' `s' p<" + "`p'; "
}
putdocx table esttable(`row',.), addrows(1)
local row= `row'+1
putdocx table esttable(`row',1) = ("`text'"), ///
font(Garamond, 11) halign(left) colspan(`col') ///
border(bottom, nil) ///
border(top)
end
/*########################################################################*/
program write_stats
version 15.1
syntax namelist(min=1), stats(string) row(integer)
//di "MODELS: `namelist'"
//di "STATS: `stats'"
//di "ROW: `row'"
local models= "`namelist'" //space sparated list of estimates
foreach stat in `stats' {
//add row for stat
putdocx table esttable(`row',.), addrows(1)
local ++row
putdocx table esttable(`row',1) = ("`stat'"), font(Garamond, 11) halign(left) bold
// get matrix of stat for each model
get_`stat' `models'
matrix S= r(S)
local col= 2
foreach mod in `models' {
if ("`stat'"!="N") {
local text: display %-12.1f S[rownumb(S,"`stat'"),colnumb(S,"`mod'")]
}
else {
local text: display %-12.0gc S[rownumb(S,"`stat'"),colnumb(S,"`mod'")]
}
putdocx table esttable(`row',`col') = (strtrim("`text'")), font(Garamond, 11) halign(left)
local ++col
}
}
end
/*########################################################################*/
program get_N, rclass
version 15.1
syntax namelist(min=1)
local models= "`namelist'" //space sparated list of estimates
//create a matrix for storing statistics
local nummods: list sizeof models
matrix Y= J(1,`nummods', .)
matrix colnames Y = `models'
matrix rownames Y = N
//loop over models and get each statistic in stats and store in S
foreach model in `models' {
//restore model to acces e()
qui estimates restore `model'
// store value of statistics specified in arg: stats in matrix S
mat Y[rownumb(Y,"N"),colnumb(Y,"`model'")]= e(N)
}
return matrix S= Y
end
/*########################################################################*/
program get_aic, rclass
version 15.1
syntax namelist(min=1)
local models= "`namelist'" //space sparated list of estimates
//create a matrix for storing statistics
local nummods: list sizeof models
matrix Y= J(1,`nummods', .)
matrix colnames Y = `models'
matrix rownames Y = aic
//loop over models and get each statistic in stats and store in S
foreach model in `models' {
//restore model to acces e()
qui estimates restore `model'
qui estat ic
mat Z= r(S)
local val= Z[1 ,colnumb(Z,"AIC")]
mat Y[rownumb(Y,"aic"),colnumb(Y,"`model'")]= `val'
}
return matrix S= Y
end
/*########################################################################*/
program get_bic, rclass
version 15.1
syntax namelist(min=1)
local models= "`namelist'" //space sparated list of estimates
//create a matrix for storing statistics
local nummods: list sizeof models
matrix Y= J(1,`nummods', .)
matrix colnames Y = `models'
matrix rownames Y = bic
//loop over models and get each statistic in stats and store in S
foreach model in `models' {
//restore model to acces e()
qui estimates restore `model'
qui estat ic
mat Z= r(S)
local val= Z[1 ,colnumb(Z,"BIC")]
mat Y[rownumb(Y,"bic"),colnumb(Y,"`model'")]= `val'
}
return matrix S= Y
end
/*########################################################################*/
/*###############################################################################################*/
// MAIN PROGRAM
/*###############################################################################################*/
program estdocx, rclass
version 17
syntax namelist(min=1), ///
[saving(string)] ///
[inline] ///
[title(string)] ///
[COlabels(string asis)] ///
[bfmt(string)] ///
[ci(string)] ///
[star(string)] ///
[stats(string)] ///
[baselevels] ///
[keep(string)] ///
[pagesize(string)] ///
[landscape] ///
[NOPval] ///
[eform] ///
[fname(string)]
// You need to captalize all options that start with no; otherwise Stata treats at as a optionally off eg. p is of
// set local holding the names of estimates to be reported in table
local estnames= "`namelist'" //space separated list of estimates
//loop over estnames to and check that they are valid estimation result names avalaible in memory
qui estimates dir
local estimates= r(names)
foreach model in `estnames' {
if(!strmatch("`estimates'", "*`model'*")) {
di _newline(3)
di as error "ERROR: `model' is not in the list of stored estimates in memory; check the supplied model names"
di _newline
di as result "The estimates currently stored in memory are:"
estimates dir
exit _rc
}
}
local du : list dups estnames
if("`du'"!="") {
di as error "ERROR: Duplicate names of stored estimates provided to estodocx. Namelist of stored estimates must be unique"
error 197
}
// set local holding list of allowed statistics
local allowed "none N aic bic"
// default values for options if none are provided
if ("`bfmt'"=="") {
local bfmt "%04.2f"
}
else {
capture confirm numeric format `bfmt'
if(_rc!=0) {
di as error "The value provided in option bfmt(`bfmt') is not a valid Stata format"
exit _rc
}
}
if ("`ci'"!="") {
capture confirm numeric format `ci'
if(_rc!=0) {
di as error "The value provided in option ci(`ci') is not a valid Stata format"
exit _rc
}
}
if ("`saving'"=="") local saving "estdocx.docx"
if ("`pagesize'"=="") local pagesize "A4"
// if stats is provided check that all stats are allowed/implemented
if ("`stats'"!="") check_stats `stats', allowed(`allowed')
if ("`stats'"=="") local stats "N" // set default stat N if stats is not provided
if ("`stats'"=="none") local stats "" // set stat null string if stat(none)
//find out the name of the current frame used to search for labels and vlables
qui frame pwf
local datafr= r(currentframe)
/**************************************************************************/
/** Call MATA to set up frame with the desired regression table **/
/**************************************************************************/
mata: create_frame_table("`estnames'", ///
"`baselevels'", ///
"`bfmt'", ///
"`ci'", ///
"`star'", ///
"`nopval'", ///
"`eform'", ///
"`fname'", ///
"`keep'")
//find out the name of the frame holding the regression table
//after the mata routines the active frame will be the one holding the regression table
qui frame pwf
local tabfr= r(currentframe)
/**************************************************************************/
/** CREATE WORDTABLE **/
/**************************************************************************/
// if !inline first create docx in memory to hold the table
if("`inline'"=="") create_docx , pagesize(`pagesize') `landscape'
/**************************************************************************/
/** SET WIDTH OF THE TABLE **/
/**************************************************************************/
local nummodels :list sizeof estnames
// set the width of the table= nummodels + one rowheader column to display variable
// names and factor levels in case var is a factor
local totcols= `nummodels' +1
create_table `estnames', pagesize(`pagesize') title(`title') `landscape'
if (`'"`colabels'"'!="") set_headers , headers(`colabels') nummod(`nummodels')
// set border on bottom of header row of table
putdocx table esttable(1,.), border(bottom)
/**************************************************************************/
/** PRINT THE TABLE FROM FRAME */
/**************************************************************************/
//read table data from frame
local rows= _N // get the total number of rows in the frame that should be exported to word
local rowMSWord= 1 // rowindicator for MSWord table
local printed ""
// loop over rows in frame
forvalues rowframe= 1(1)`rows' {
// 1. check the type of parameter
local type= type[`rowframe']
local label= label[`rowframe']
local vlab=vlab[`rowframe']
// 2. if factor
if "`type'"=="factor" | "`type'"=="factor-interaction"{
//di "factor: `label': `vlabel'"
//add a variable header row and print varname if it has not been printed
//check if varname is in the list of printed varnames
local lab= subinstr("`label'", " ", "", .) //remove all whitespace
local print : list posof "`lab'" in printed
//di "`printed'"
// if the header is not orinted add row for varheader
if !`print' {
// add header row with varname of factor variable
putdocx table esttable(`rowMSWord',.), addrows(1)
local ++rowMSWord
putdocx table esttable(`rowMSWord',1) = ("`label'"), bold font(Garamond, 11) halign(left)
local printed "`printed' `lab'" //add varname to list of printed headers
}
// print row with params for factor-level
putdocx table esttable(`rowMSWord',.), addrows(1)
local ++rowMSWord
putdocx table esttable(`rowMSWord',1) = ("`vlab'"), italic font(Garamond, 10) halign(center)
//loop over columns of frame and set cell values of table for factor
forvalues col=2/`totcols' {
local estnum= `col'-1
local estname: word `estnum' of `estnames'
putdocx table esttable(`rowMSWord',`col') = (strtrim(`estname'[`rowframe'])), font(Garamond, 10) halign(left)
}
}
else if "`type'"=="continious" | "`type'"=="continious-interaction" | "`type'"=="const" {
//di "continious: `label'"
putdocx table esttable(`rowMSWord',.), addrows(1)
local ++rowMSWord
putdocx table esttable(`rowMSWord',1) = ("`label'"), bold font(Garamond, 11) halign(left)
//loop over columns of frame and set cell values of table for continious
forvalues col=2/`totcols' {
local estnum= `col'-1
local estname: word `estnum' of `estnames'
putdocx table esttable(`rowMSWord',`col') = (strtrim(`estname'[`rowframe'])), ///
font(Garamond, 10) halign(left)
}
}
}
// set border at bottom beta table
putdocx table esttable(`rowMSWord',.), border(bottom)
/**************************************************************************/
// ADD STATS TO BOTTOM OF TABLE IF stats!=null
/**************************************************************************/
if ("`stats'"!="") write_stats `estnames', stats(`stats') row(`rowMSWord')
/**************************************************************************/
// print a legend with significance values
/**************************************************************************/
qui putdocx describe esttable
if("`star'"!="" & "`nopval'"=="") write_legend, star(`star') row(`r(nrows)') col(`r(ncols)')
/**************************************************************************/
/** Store tabel info in r() if in inline mode else save to standalone file */
/**************************************************************************/
if("`inline'"!="") {
qui putdocx describe esttable
return local tabname= "esttable"
return scalar tabrows= r(nrows)
return scalar tabcols= r(ncols)
}
else {
// Save document to standalone file
capture noisily putdocx save "`saving'", replace
if _rc!=0 {
display as error "Unable to save `saving'"
display as error "Make sure you do not have a worddocument with the same filename open (i.e. `saving')"
display as error "If a document with the same name is open this will prohibit Stata to save the file to disc."
display as error "If that is the case close the Wordfile and run program again."
exit _rc
}
}
/**************************************************************************/
/** Garbage collection **/
/**************************************************************************/
//matrix drop _all
end
version 17
mata: mata set matastrict on
mata: mata set matalnum on
// macroed types
local boolean real
local TRUE 1
local FALSE 0
local SS string scalar
local SCV string colvector
local RS real scalar
mata:
/*#######################################################################################*/
// STRUCTURES
/*#######################################################################################*/
/**************************************************************************
STRUCTURE paramvar
**************************************************************************/
struct paramvar {
string scalar vartype
string scalar varname
string scalar label
string scalar vlab
string scalar prefix //entire string before . in paramtxt
string scalar level
real scalar base
real scalar omitted
}
/*#######################################################################################*/
// CLASS parameter
/*#######################################################################################*/
class parameter {
public:
string scalar paramtype // type of paramter.. continious, factor, interaction
string scalar comblabel // combined label of all variables forming the paramter
string scalar combvlab // combined label of all included variabels/levels
string scalar paramtxt //complete string forming the paramter
real scalar interaction //boolean indicating if it is an interaction
string vector intervars
struct paramvar vector vars //vector of different variables forming the parameter
void setup()
void print()
struct paramvar parsevar()
}
/*#######################################################################################
// CLASS parameter FUNCTIONS
#######################################################################################*/
void parameter::setup(string scalar user_txt) {
real scalar i
struct paramvar scalar P
//make sure all propreties are null when setup is run
this.comblabel= this.combvlab = this.paramtype = this.paramtxt = ""
this.interaction= .
this.paramtxt= user_txt // text defining the complete paramteter
//check if parameter is an interaction
this.interaction= strrpos(this.paramtxt,"#") > 0
if (this.interaction) {
//"do complicated things for interaction paramters"
this.intervars=tokens(subinstr(this.paramtxt, "#", " ") ) //matrix with varnames forming the interaction
// fill colvector this.vars with strcutures for each varaible in interaction stored in intervars
// set this vars to a new vector of struct paramvars of length= this.intervars
this.vars = paramvar(length(this.intervars))
for (i=1; i<=length(this.intervars); i++) {
P= this.parsevar(this.intervars[i]) //create struct paramvar using string in this.intervars
this.vars[i]= P // add struct to vector this.vars
}
// form the combined label and value-label for the interaction
// intercations containing at least one factor should have vlab
for (i=1; i<=length(this.vars); i++) {
if (i > 1) this.comblabel= this.comblabel + " * " + this.vars[i].label
else this.comblabel= this.vars[i].label
// if vlab is null do nothing
// if vlab !null and comb !null add "*" + vlab to comb
// if vlab !null and comb null add vlab to comb
if (this.combvlab=="" & this.vars[i].vlab!="") {
this.combvlab= this.vars[i].vlab
}
else if(this.combvlab!="" & this.vars[i].vlab!="") {
this.combvlab= this.combvlab + " * " + this.vars[i].vlab
}
else {
// do nothing
}
}
//check if any of the incuded variables are factors this.combvlab will not be null
if(this.combvlab=="") this.paramtype= "continious-interaction"
else this.paramtype= "factor-interaction"
}
else {
//"do easy things for factors and continious variables"
//create a single element vector with one paramvar struct
this.vars = paramvar(1)
this.vars= this.parsevar(this.paramtxt)
this.comblabel= this.vars[1].label
this.combvlab= this.vars[1].vlab
this.paramtype= this.vars[1].vartype
}
}
/***************************************************************************
Function
****************************************************************************/
struct paramvar parameter::parsevar(string scalar vartext){
struct paramvar scalar P
real scalar rcode
string scalar cmd
// assign the part of the string efter . to P.varname
P.varname= substr(vartext , strrpos(vartext,".")+1 , strlen(vartext))
// assign part of string before . to P.prefix
P.prefix= substr(vartext , 1 , strrpos(vartext,".")-1 )
//check that P.varname is a varaible in the dataset
cmd= "confirm variable " + P.varname
//function will return non-zero (error=111) if varname does not exist
// set type and name and then exit
if (_stata(cmd, 1)) {
P.vartype= "const"
P.label= P.varname
return(P)
}
//check if prefix contains numeric character then it is a factor
if (regexm(P.prefix, "[0-9]")) {
P.vartype= "factor"
// check if prefix is base
P.base= strrpos(P.prefix,"b") > 0
// check if prefix is ommitted
P.omitted= strrpos(P.prefix,"o") > 0
// check if it is bn than it is not base or omitted
if(regexm(P.prefix, "bn")) {
P.base= `FALSE'
P.omitted= `FALSE'
}
//get only the numeric value in prefix if it contains letters to get valuelabel with st_varvaluelabel()
// match the numbers with regexm and then return them with regexs
if (regexm(P.prefix, "[0-9]+")) P.level= regexs(0)
// check that value labels are set and set vlab to correct value label in P.vlab
if (st_varvaluelabel(P.varname)!="") P.vlab = st_vlmap(st_varvaluelabel(P.varname), strtoreal(P.level))
else P.vlab = P.level
// sometimes the value lable is set but is null string => set to level of factor
if (P.vlab=="") P.vlab = P.level
}
else if (P.prefix=="" | P.prefix=="c" | P.prefix=="co") {
P.vlab= "" // paramter is not factor vlab should be null
P.vartype= "continious"
//contionios variables have no base-level
P.base= 0
// check if paramter is omitted
P.omitted= strrpos(P.prefix,"o") > 0
}
else {
_error(3300, "Parameter contains a value not implemented in estdocx")
}
// check that a varlabel is set else return varname in P.label
if (st_varlabel(P.varname)!="") P.label= st_varlabel(P.varname)
else P.label= P.varname
return(P)
}
/***************************************************************************
Function
****************************************************************************/
void parameter::print() {
real scalar i
printf("{txt}___________________________________________________________\n")
for(i=1; i<=length(this.vars); i++) {
printf("{txt}---Structure: %f ---------------------------------\n", i)
printf("{txt}vartype is:{result} %s\n", this.vars[i].vartype)
printf("{txt}varname is:{result} %s\n", this.vars[i].varname)
printf("{txt}label is:{result} %s\n", this.vars[i].label)
printf("{txt}vlab is:{result} %s\n", this.vars[i].vlab)
printf("{txt}prefix is:{result} %s\n", this.vars[i].prefix)
printf("{txt}level is:{result} %s\n", this.vars[i].level)
printf("{txt}base is:{result} %f\n", this.vars[i].base)
printf("{txt}omitted is:{result} %f\n", this.vars[i].omitted)
}
printf("{txt}--- Object: --------------------------------------\n")
printf("{txt}paramtxt is:{result} %s\n", this.paramtxt)
printf("{txt}paramtype is:{result} %s\n", this.paramtype)
printf("{txt}comblabel is:{result} %s\n", this.comblabel)
printf("{txt}combvlab is:{result} %s\n", this.combvlab)
printf("{txt}interaction is:{result} %f\n", this.interaction)
printf("{txt}___________________________________________________________\n")
}
/*#######################################################################################*/
// CLASS model
/*#######################################################################################*/
class model {
public:
//public vars
string scalar estname // name of a stored estimate in memory
real matrix modscalars // matrix with all data for model
string colvector statistics // list of statistics returned by matrixcolstripe(r(table))
string colvector parameters // full list of parameters from matrixrowstripe(r(table))
string colvector levels // colvector with base and omitted removed used to match params across models
real colvector interactions // vector of boolean values indicating if parameter[row] is interaction
real colvector base // vector of boolean values indicating if parameter[row] is base
real colvector omitted // vector of boolean values indicating if parameter[row] is omitted
real colvector constfree // vector of boolean values indicating if parameter[row] is _const or free
//public functions
void setup() // setup takes a name of a stored estimate in memory
void print() // prints object properties to screen
`RS' get_beta() // returns beta as real for a given level
`RS' get_pvalue() // returns pvalue as real for a given level
`RS' get_ll() // returns lower bound of ci as real for a given level
`RS' get_ul() // returns upper bound of ci as real for a given level
`boolean' scalar get_base() // returns boolean==TRUE if level is a base
`boolean' scalar get_intr() // returns boolean==TRUE if level is a interaction
`boolean' scalar get_eform() // returns boolean==TRUE if level is in eform
private:
// private vars
class AssociativeArray scalar rtable // array to save rtable-data using string keys: parameter, statistic
// private functions
void set_levels()
void set_interactions()
void set_base()
void set_omitted()
void set_constfree()
}
/*#######################################################################################
// CLASS model FUNCTIONS
#######################################################################################*/
void model::setup(string scalar estname) {
string scalar com
real scalar i, ii
//get matrix rtable created by running estimates replay estname
com= "estimates replay " + estname
stata(com, 1)
stata("mat M= r(table)")
//stata("mat li M")
stata("mat M= M'")
modscalars= st_matrix("M")
parameters= st_matrixrowstripe("M") //get varlist of model
statistics= st_matrixcolstripe("M") //get stats of model
statistics= statistics[.,2] //remove first col that is all missing
parameters= parameters[.,2] //remove first col that is all missing
set_levels() //set the string vector levels contining paramters with base/omitted stripped
set_interactions() //set the boolean vector indicating if parameter/level is an interaction
set_base() //set the boolean vector indicating if parameter/level is base/omitted
set_constfree() //set the boolean vector indicating if parameter/level is _const or free
// fill array rtable with data from modscalars for each statistics
// reinitate the assositative array as array with 3 dimention string keys
this.rtable.reinit("string", 2)
this.rtable.notfound(.)
for (ii=1; ii<=length(this.statistics); ii++) {
for (i=1; i<=length(this.levels); i++) {
this.rtable.put((this.statistics[ii], this.levels[i]), this.modscalars[i,ii])
}
}
}
/***************************************************************************
Function returns boolean TRUE if supplied level is a baselevel
****************************************************************************/
`boolean' scalar model::get_base(`SS' level) {
`RS' i
i= selectindex(regexm(this.levels, "^" + level + "$"))
//In cases where level is not in the list of model levels selectindex()
// will return J(0,0,.) an empty real vector and not a scalar
if(orgtype(i) == "scalar") return(this.base[i])
else return(`FALSE')
}
/***************************************************************************
Function returns boolean TRUE if supplied level is an interaction
****************************************************************************/
`boolean' scalar model::get_intr(`SS' level) {
`RS' i
i= selectindex(regexm(this.levels, "^" + level + "$"))
//In cases where level is not in the list of model levels selectindex()
// will return J(0,0,.) an empty real vector and not a scalar
if(orgtype(i) == "scalar") return(this.interactions[i])
else return(`FALSE')
}
/***************************************************************************
Function returns boolean TRUE if supplied level is in eform
****************************************************************************/
`boolean' scalar model::get_eform(`SS' level) {
return(this.rtable.get(("eform", level)))
}
/***************************************************************************
Function returns beta-value for supplied level
****************************************************************************/
`RS' model::get_beta(`SS' level) {
return(this.rtable.get(("b", level)))
}
/***************************************************************************
Function returns p-value string param
****************************************************************************/
`RS' model::get_pvalue(`SS' level) {
return(this.rtable.get(("pvalue", level)))
}
/***************************************************************************
Function returns upper bound of ci as real
****************************************************************************/
`RS' model::get_ul(`SS' level) {
return(this.rtable.get(("ul", level)))
}
/***************************************************************************
Function returns lower bound of ci as real
****************************************************************************/
`RS' model::get_ll(`SS' level) {
return(this.rtable.get(("ll", level)))
}
/***************************************************************************
Function sets the boolean vector indicating if parameter/level is _const or free
****************************************************************************/
void model::set_constfree() {
real scalar r
this.constfree= J(length(this.parameters), 1, .)
for (r=1; r<=length(this.parameters); r++) {
// match paramaters that has _/ at beginning of string
this.constfree[r]= regexm(this.parameters[r], "^[_/]")
}
}
/***************************************************************************
Function sets the string vector levels contining pramters with base/omitted stripped
****************************************************************************/
void model::set_levels() {
real scalar r
string scalar param
this.levels= J(length(this.parameters), 1, "")
for (r=1; r<=length(this.parameters); r++) {
param= this.parameters[r]
// remove base and omitted charathers
while(regexm(param, "[bo]+\.")) param= regexr(param, "[bo]+\.", ".")
// remove contionious chanter in intercations
while(regexm(param, "[c]+\.")) param= regexr(param, "[c]+\.", "")
this.levels[r]=param
}
}
/***************************************************************************
Function sets the boolean vector indicating if parameter/level is an interaction
****************************************************************************/
void model::set_interactions() {
`RS' r
this.interactions= J(length(this.parameters), 1, .)
for (r=1; r<=length(this.parameters); r++) {
this.interactions[r]= (strrpos(this.parameters[r],"#") > 0)
}
}
/***************************************************************************
Function sets the boolean vector indicating if parameter/level is base/omitted
****************************************************************************/
void model::set_base() {
`RS' r, i, baseom
`SS' prefix
`SCV' intervars
this.base= J(length(this.parameters), 1, .)
for (r=1; r<=length(this.parameters); r++) {
if (this.interactions[r]) {
//check if all incuded factors in interaction are base or omitted
intervars=tokens(subinstr(this.parameters[r], "#", " ") ) //matrix with varnames forming the interaction
baseom= 0
for (i=1; i<=length(intervars); i++) {
// assign part of string before . to P.prefix
prefix= substr(intervars[i] , 1 , strrpos(intervars[i],".")-1 )
// increment bases if it is a base or omitted factor but not nobase
if((strrpos(prefix,"b") > 0 | strrpos(prefix,"o") > 0) & !strrpos(prefix,"n")) baseom++
}
// check if all factors are base or omitted
this.base[r]= (length(intervars)==baseom)
}
else { // if it is not an interaction
prefix= substr(this.parameters[r] , 1 , strrpos(this.parameters[r],".")-1)
this.base[r]=(strrpos(prefix,"b") > 0 | strrpos(prefix,"o") > 0)
}
}
}
/***************************************************************************
Function prints object properties to screen
****************************************************************************/
void model::print() {
`SS' tabrowtxt, colwith
`RS' i
colwith=strofreal(max(strlen(this.parameters))+10)
colwith
//this.parameters, this.levels, strofreal(this.interactions), strofreal(this.base))
printf("{txt}--- Object model: --------------------------------------\n")
printf("{txt}1234{c |}6789{c |}{txt}1234{c |}6789{c |}{txt}1234{c |}6789{c |}")
printf("{txt}1234{c |}6789{c |}{txt}1234{c |}6789{c |}{txt}1234{c |}6789{c |}")
printf("{txt}1234{c |}6789{c |}{txt}1234{c |}6789{c |}{txt}1234{c |}6789{c |}\n\n")
//hline 1
printf("{hline 4 }{c +}") //5
printf("{hline 34}{c +}") //40
printf("{hline 3 }{c +}") //44
printf("{hline 3 }{c +}") //48