anonymous-submission-acl2025 commited on
Commit
43c4598
·
1 Parent(s): 53589fc
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. 110/paper.pdf +3 -0
  2. 110/replication_package/README.pdf +3 -0
  3. 110/replication_package/replication/Data/Raw/allcity_info.dta +3 -0
  4. 110/replication_package/replication/Data/Raw/baidu.dta +3 -0
  5. 110/replication_package/replication/Data/Raw/city_info.dta +3 -0
  6. 110/replication_package/replication/Data/Raw/daily_monitor_api.dta +3 -0
  7. 110/replication_package/replication/Data/Raw/enf_info.dta +3 -0
  8. 110/replication_package/replication/Data/Raw/firm_info.dta +3 -0
  9. 110/replication_package/replication/Data/Raw/lights.dta +3 -0
  10. 110/replication_package/replication/Data/Raw/mayor.dta +3 -0
  11. 110/replication_package/replication/Data/Raw/monitor_city_long.dta +3 -0
  12. 110/replication_package/replication/Data/Raw/monitor_info.dta +3 -0
  13. 110/replication_package/replication/Data/Raw/non-asif.dta +3 -0
  14. 110/replication_package/replication/Data/Raw/pm.dta +3 -0
  15. 110/replication_package/replication/Data/Raw/pm_pix.dta +3 -0
  16. 110/replication_package/replication/Data/Raw/weather_daily.dta +3 -0
  17. 110/replication_package/replication/Data/age_2017.dta +3 -0
  18. 110/replication_package/replication/Data/age_year.dta +3 -0
  19. 110/replication_package/replication/Data/city_enf.dta +3 -0
  20. 110/replication_package/replication/Data/city_enf_rd.dta +3 -0
  21. 110/replication_package/replication/Data/city_pm.dta +3 -0
  22. 110/replication_package/replication/Data/city_pm_rd.dta +3 -0
  23. 110/replication_package/replication/Data/enf.dta +3 -0
  24. 110/replication_package/replication/Data/firm_enf.dta +3 -0
  25. 110/replication_package/replication/Data/mayor_panel.dta +3 -0
  26. 110/replication_package/replication/Data/monitor_api.dta +3 -0
  27. 110/replication_package/replication/Data/monitor_pix.dta +3 -0
  28. 110/replication_package/replication/Data/monthly_api.dta +3 -0
  29. 110/replication_package/replication/Data/pix.dta +3 -0
  30. 110/replication_package/replication/Data/share.dta +3 -0
  31. 110/replication_package/replication/Data/weather_monthly.dta +3 -0
  32. 110/replication_package/replication/Data/weather_quarterly.dta +3 -0
  33. 110/replication_package/replication/Data/wind_quarterly.dta +3 -0
  34. 110/replication_package/replication/Do-file/Appendix.do +1564 -0
  35. 110/replication_package/replication/Do-file/Figure.do +177 -0
  36. 110/replication_package/replication/Do-file/Install.do +39 -0
  37. 110/replication_package/replication/Do-file/MakeData.do +351 -0
  38. 110/replication_package/replication/Do-file/Master.do +19 -0
  39. 110/replication_package/replication/Do-file/Table.do +284 -0
  40. 110/replication_package/replication/Do-file/classify.py +110 -0
  41. 110/replication_package/replication/ado/personal/ols_spatial_HAC.ado +408 -0
  42. 110/replication_package/replication/ado/personal/reg2hdfespatial.ado +202 -0
  43. 110/replication_package/replication/ado/plus/_/_eststo.ado +28 -0
  44. 110/replication_package/replication/ado/plus/_/_eststo.hlp +1 -0
  45. 110/replication_package/replication/ado/plus/b/binscatter.ado +1048 -0
  46. 110/replication_package/replication/ado/plus/b/binscatter.sthlp +332 -0
  47. 110/replication_package/replication/ado/plus/b/binslogit.ado +2394 -0
  48. 110/replication_package/replication/ado/plus/b/binslogit.sthlp +427 -0
  49. 110/replication_package/replication/ado/plus/b/binsprobit.ado +2390 -0
  50. 110/replication_package/replication/ado/plus/b/binsprobit.sthlp +428 -0
110/paper.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:07d13bb63519a2b71d947cad77a7fdce405a8fe8149948a912d60ec73311c0f7
3
+ size 1047016
110/replication_package/README.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78a718f187ebdc73405e2c0fd25b19f5f355ddebff74865072cbb606f9ad750e
3
+ size 83852
110/replication_package/replication/Data/Raw/allcity_info.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:12a4cb5b0d282c620703079f8249182f5be48ba77acc8dccdcbd91201b396f30
3
+ size 26619
110/replication_package/replication/Data/Raw/baidu.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1592c3d50dfd55c71dc6e941b060ad427988755640cd8dd629e5ceb10a616e9d
3
+ size 1610593
110/replication_package/replication/Data/Raw/city_info.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a82a01813262f00682801f8d1b6cc82495ab1b91d5b0cad81c45617fa5ecf32
3
+ size 157347
110/replication_package/replication/Data/Raw/daily_monitor_api.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:601b057fbd7bb156dc6c09ac76944951b5f5fda616e716f150389a656325790f
3
+ size 73326101
110/replication_package/replication/Data/Raw/enf_info.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:725cfabc1df243f8581550753f1dc4ca837a9b3cfadc91cdbee5334da91884a7
3
+ size 125241117
110/replication_package/replication/Data/Raw/firm_info.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:219e4405db12a981ae0968460f46759c4ca55ac25bae511a7452ecaab33ecf55
3
+ size 48410992
110/replication_package/replication/Data/Raw/lights.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:660809efe234fe8cce30755a42884a612c898be7f84e58d442fd630fd2a3f7cb
3
+ size 590633
110/replication_package/replication/Data/Raw/mayor.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:049e787aab43af46ed8d7c119813ddbd24aa6f3d520b83a47572ef1e1cbf22b3
3
+ size 158452
110/replication_package/replication/Data/Raw/monitor_city_long.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9a62866ac354457cc8d873bc4ee89eb50ccdc662d93700bba83c8ad61265cd4c
3
+ size 398439
110/replication_package/replication/Data/Raw/monitor_info.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:72f23e3fbfa4045e19762601b67364054560599b0229375e6bace842a2d9cd9a
3
+ size 17207
110/replication_package/replication/Data/Raw/non-asif.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2dae2c0e50bb65703d9f7b7adb60708170aa9b95451792a5a756b87b26401b5
3
+ size 145814
110/replication_package/replication/Data/Raw/pm.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b48d012c21a4b6d2640315da680593a4984956da648010306a5aff782c8a06c6
3
+ size 402981
110/replication_package/replication/Data/Raw/pm_pix.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:161a1cd39bba8a13dd987fe56cb957571ceb1570f536957524550a3723c6951d
3
+ size 296456487
110/replication_package/replication/Data/Raw/weather_daily.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4ec43c966d187b8e8bf642914cdd514a0b67907ceceaf830a86567d77f1f16e5
3
+ size 356358846
110/replication_package/replication/Data/age_2017.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:075f53223d92b3ec57941b91f325a70b5a61f8097336d9a98ef72b83d2e83526
3
+ size 9971
110/replication_package/replication/Data/age_year.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cbacc1ada89b49d026131d50dc255fefa6a1302d9f4577dc1ea9aaa4fa7dfbe2
3
+ size 17228
110/replication_package/replication/Data/city_enf.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7736abea6375079aa347b33c17db4eb6616fa420b53834820fdcff4c7805f225
3
+ size 5212280
110/replication_package/replication/Data/city_enf_rd.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26c6b8b5d881fa88d1312b4206033bd85a1181741cc116a23ef11f9b739cd0bd
3
+ size 10401144
110/replication_package/replication/Data/city_pm.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b40fbf0c7ac82654fd5d45a40fcd4490a79a566cdf5d84e7eb301d7d57e35e84
3
+ size 14746346
110/replication_package/replication/Data/city_pm_rd.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5e449b5afef866304b825c89830b1c1e2afc13a8f59a921c5d29a5a73f6bd2d0
3
+ size 29496042
110/replication_package/replication/Data/enf.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e2607fee216a4488bf52da3a9833a0b9e86a8da4066af5ea57f0ebb3efd53540
3
+ size 447505
110/replication_package/replication/Data/firm_enf.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c057d3ef97271990288ae4773bdc26d1be58b65e269c61b958b1319c41a7c257
3
+ size 1790795729
110/replication_package/replication/Data/mayor_panel.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:943e087105600af41c4686d6b327678a454fa3ccf6b0a955203eaf7690781fac
3
+ size 5591041
110/replication_package/replication/Data/monitor_api.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ee5a6f082c4897a3f25a001b9a89559c5e54fdf64016ac6b445732163f01142b
3
+ size 1165784
110/replication_package/replication/Data/monitor_pix.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b480cdfd1bb7de424b67048ebc5e42a5418a2d44eb1dd336e3342f6df9dfb51c
3
+ size 967587
110/replication_package/replication/Data/monthly_api.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e581d51abea4737c85604861f62fc370e6908c8ca28442b2891ae063bf5d6fc
3
+ size 1930462
110/replication_package/replication/Data/pix.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a307757e58c7bc113f829f0494542ee98f1d00a5795469b2d4e78e782117b234
3
+ size 221127
110/replication_package/replication/Data/share.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e01d6591a4efbed529daf66bd71fec07bbda9093a022bb874f9613f493f2eca4
3
+ size 11366
110/replication_package/replication/Data/weather_monthly.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:25ccb314e369ee87ed719872313ea3ed2b91d493f8bdd2ca2e44b619a579656f
3
+ size 297844
110/replication_package/replication/Data/weather_quarterly.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f93b8adcffe878426f1c004bbda5d36daa347fbc78c8c7651a55bd12232d32b4
3
+ size 122260
110/replication_package/replication/Data/wind_quarterly.dta ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9c1a0b439edc00aa35d7b8a42cdada8c415b15774c026e396a4bdd6f699697e9
3
+ size 59316
110/replication_package/replication/Do-file/Appendix.do ADDED
@@ -0,0 +1,1564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * Set Directory
2
+ clear
3
+ set more off
4
+ set scheme s1mono
5
+
6
+ cd "$path"
7
+ global data_files "$path/Data"
8
+ global out_files "$path/output"
9
+
10
+ **==============================================================================
11
+ * Table A1
12
+ use "$data_files/Raw/allcity_info", clear
13
+
14
+ label variable pm25 "AOD"
15
+ label variable number "\# Monitors"
16
+ label variable area "Size of Built-up Area (km2)"
17
+ label variable pop "Urban Population (10,000)"
18
+
19
+ eststo clear
20
+ estpost tabstat pm25 number area pop, by(mainsample) statistics(mean sd) columns(statistics) listwise nototal
21
+ esttab using "$out_files/TableA1.tex", replace tex main(mean) aux(sd) nogaps nodepvar compress fragment nostar noobs unstack nonote nomtitle label
22
+
23
+ **==============================================================================
24
+ * Table C1
25
+ use "$data_files/firm_enf.dta", clear
26
+ keep if min_dist<50 & starty<=2010
27
+ drop if revenue == .
28
+ drop if key == .
29
+
30
+ label variable any_air "Any Air Pollution Enforcement"
31
+ label variable any_air_shutdown "\quad Suspension"
32
+ label variable any_air_fine "\quad Fine"
33
+ label variable any_air_renovate "\quad Upgrading"
34
+ label variable any_air_warning "\quad Warning"
35
+ label variable air "\# Air Pollution Enforcement"
36
+ label variable any_water "Any Water Pollu. Enforc."
37
+ label variable any_waste "Any Solid Waste Pollu. Enforc."
38
+ label variable any_proc "Any Procedure Pollu. Enforc."
39
+
40
+ label variable min_dist_10 "Monitor within 10 km"
41
+ label variable min_dist "Distance to Monitor (km)"
42
+ label variable starty "Year Started"
43
+ label variable employment "Employment"
44
+ label variable revenue "Revenue"
45
+ label variable up "Upwind Firms"
46
+
47
+ eststo clear
48
+ estpost summarize any_air* air any_water any_waste any_proc up
49
+ esttab using "$out_files/TableC1a1.tex", replace cells("mean(fmt(a2)) sd(fmt(a2)) count") noobs nolines nogaps nodepvar compress fragment nonumbers label mlabels(none) tex
50
+ display "Periods: "
51
+ display "Frequency: "
52
+
53
+ keep if year==2010 & quarter==1
54
+
55
+ gen state = (ownership==1 | ownership==2)
56
+ gen private = (ownership==3)
57
+ gen foreign = (ownership==9)
58
+ gen rest = (ownership==4|ownership==5)
59
+
60
+ label variable state "Owner: SOEs"
61
+ label variable private "Owner: Private"
62
+ label variable foreign "Owner: Foreign"
63
+ label variable rest "Owner: Other"
64
+
65
+ eststo clear
66
+ estpost summarize min_dist_10 min_dist starty state private foreign rest employment revenue
67
+ esttab using "$out_files/TableC1a2.tex", replace cells("mean(fmt(a2)) sd(fmt(a2)) count") noobs nolines nogaps nodepvar compress fragment nonumbers label mlabels(none) tex
68
+ display "Periods: "
69
+ display "Frequency: "
70
+
71
+ use "$data_files/city_pm.dta", clear
72
+ drop if pm25 == .
73
+
74
+ label variable number "\# Monitors"
75
+ label variable area "Size of Built-up Area (km2)"
76
+ label variable pop "Urban Population (10,000)"
77
+ label variable age_year "Age of the Mayor"
78
+ label variable pre "Precipitation (mm)"
79
+ label variable tem_mean "Mean Temperature"
80
+ label variable pm25 "Aerosol Optical Depth"
81
+
82
+ eststo clear
83
+ estpost summarize number area pop age_year pre tem_mean pm25
84
+ esttab using "$out_files/TableC1b1.tex", replace cells("mean(fmt(a2)) sd(fmt(a2)) count") noobs nolines nogaps nodepvar compress fragment nonumbers label mlabels(none) tex
85
+ display "Periods: "
86
+ display "Frequency: "
87
+
88
+ use "$data_files/city_pm.dta", clear
89
+ label variable post1 "Post"
90
+ label variable number "\# Mon"
91
+ label variable number_iv "Min \# Mon"
92
+
93
+ merge 1:1 city_cn year month using "$data_files/Raw/baidu.dta"
94
+ keep if _merge == 3
95
+ drop _merge
96
+
97
+ label variable sear_freq_w1 "Search Index: air pollution"
98
+ label variable sear_freq_w2 "Search Index: haze/smoke"
99
+ label variable sear_freq_w3 "Search Index: PM25"
100
+ label variable sear_freq_w4 "Search Index: air mask"
101
+ label variable sear_freq_w5 "Search Index: air purifier"
102
+
103
+ eststo clear
104
+ estpost summarize sear*
105
+ esttab using "$out_files/TableC1b3.tex", replace cells("mean(fmt(a2)) sd(fmt(a2)) count") noobs nolines nogaps nodepvar compress fragment nonumbers label mlabels(none) tex
106
+ display "Periods: "
107
+ display "Frequency: "
108
+
109
+ use "$data_files/city_enf.dta", clear
110
+
111
+ gen any_air_total = any_air+any_air_rest
112
+ label variable any_air_total "\# Firms Any Air Pollu. Enfor. (incl non-ASIF)"
113
+ label variable any_air "\# Firms Any Air Pollu. Enfor."
114
+
115
+ eststo clear
116
+ estpost summarize any_air any_air_total
117
+ esttab using "$out_files/TableC1b2.tex", replace cells("mean(fmt(a2)) sd(fmt(a2)) count") noobs nolines nogaps nodepvar compress fragment nonumbers label mlabels(none) tex
118
+ display "Periods: "
119
+ display "Frequency: "
120
+
121
+ use "$data_files/monitor_api.dta", clear
122
+
123
+ label variable pm25api "Particulate Matter 2.5 (PM$\_2.5$)"
124
+ label variable pm10api "Particulate Matter 10 (PM$\_10$))"
125
+ label variable AQI "Air Quality Index (AQI) "
126
+
127
+ eststo clear
128
+ estpost summarize pm25api pm10api AQI
129
+ esttab using "$out_files/TableC1c.tex", replace cells("mean(fmt(a2)) sd(fmt(a2)) count") noobs nolines nogaps nodepvar compress fragment nonumbers label mlabels(none) substitute(\_ _) tex
130
+
131
+ **==============================================================================
132
+ * Table C4
133
+ use "$data_files/monitor_api.dta", clear
134
+
135
+ gen log_pm25api = log(pm25api)
136
+ gen log_pm10api = log(pm10api)
137
+ gen log_aqi = log(AQI)
138
+ replace log_aqi = . if log_pm25api == .
139
+
140
+ rename pm25 AOD
141
+ label variable AOD "AOD"
142
+
143
+ eststo clear
144
+ reghdfe log_pm25api AOD pre tem_mean, a(monitor_id year#month) cl(city_id)
145
+ eststo A
146
+ estadd ysumm, mean
147
+ reghdfe log_pm10api AOD pre tem_mean, a(monitor_id year#month) cl(city_id)
148
+ eststo B
149
+ estadd ysumm, mean
150
+ reghdfe log_aqi AOD pre tem_mean, a(monitor_id year#month) cl(city_id)
151
+ eststo C
152
+ estadd ysumm, mean
153
+ esttab A B C using "$out_files/TableC4.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(AOD) drop() stats(ymean N, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
154
+
155
+ **==============================================================================
156
+ * Table C5
157
+ use "$data_files/firm_enf.dta", clear
158
+ drop if revenue == .
159
+ drop if key == .
160
+ keep if min_dist<50 & starty<=2010 & time==1
161
+
162
+ gen twodigit = int(industry/100)
163
+
164
+ lab def twodigit_lb 6 "Mining and Washing of Coal & 6" ///
165
+ 7 "Extraction of Petroleum and Natural Gas & 7" ///
166
+ 8 "Mining and Processing of Ferrous Metal Ores & 8" ///
167
+ 9 "Mining and Processing of Non-Ferrous Metal Ores & 9" ///
168
+ 10 "Mining and Processing of Nonmetallic Mineral & 10" ///
169
+ 11 "Mining Support & 11" ///
170
+ 12 "Other Mining & 12" ///
171
+ 13 "Agricultural and Sideline Food Processing & 13" ///
172
+ 14 "Fermentation & 14" ///
173
+ 15 "Beverage Manufacturing & 15" ///
174
+ 16 "Tobacco Manufacturing & 16" ///
175
+ 17 "Textile Mills & 17" ///
176
+ 18 "Wearing Apparel and Clothing Accessories Manufacturing & 18" ///
177
+ 19 "Leather, Fur and Related Products Manufacturing & 19" ///
178
+ 20 "Wood and Bamboo Products Manufacturing & 20" ///
179
+ 21 "Furniture Manufacturing & 21" ///
180
+ 22 "Products Manufacturing & 22" ///
181
+ 23 "Printing and Reproduction of Recorded Media & 23" ///
182
+ 24 "Education and Entertainment Articles Manufacturing & 24" ///
183
+ 25 "Petrochemicals Manufacturing & 25" ///
184
+ 26 "Chemical Products Manufacturing& 26" ///
185
+ 27 "Medicine Manufacturing & 27" ///
186
+ 28 "Chemical Fibers Manufacturing & 28" ///
187
+ 29 "Rubber Products Manufacturing & 29" ///
188
+ 30 "Plastic Products Manufacturing & 30" ///
189
+ 31 "Non-Metallic Mineral Products Manufacturing & 31" ///
190
+ 32 "Iron and Steel Smelting & 32" ///
191
+ 33 "Non-Ferrous Metal Smelting & 33" ///
192
+ 34 "Fabricated Metal Products Manufacturing & 34" ///
193
+ 35 "General Purpose Machinery Manufacturing & 35" ///
194
+ 36 "Special Purpose Machinery Manufacturing & 36" ///
195
+ 37 "Transport Equipment Manufacturing & 37" ///
196
+ 38 "Electrical machinery and equipment Manufacturing & 38" ///
197
+ 39 "Electrical Equipment Manufacturing & 39" ///
198
+ 40 "Computers and Electronic Products Manufacturing & 40" ///
199
+ 41 "General Instruments and Other Equipment Manufacturing & 41" ///
200
+ 42 "Craft-works Manufacturing & 42" ///
201
+ 43 "Renewable Materials Recovery & 43" ///
202
+ 44 "Electricity and Heat Supply & 44" ///
203
+ 45 "Gas Production and Supply & 45" ///
204
+ 46 "Water Production and Supply & 46", add
205
+
206
+ label values twodigit twodigit_lb
207
+
208
+ eststo clear
209
+
210
+ estpost tabulate twodigit
211
+ esttab using "$out_files/TableC5.tex", replace tex cells("b(label(freq)) pct(fmt(2))") varlabels(`e(labels)', blist(Total)) nolines nogaps compress fragment label
212
+
213
+
214
+ **==============================================================================
215
+ * Table C6
216
+ use "$data_files/Raw/daily_monitor_api.dta", clear
217
+
218
+ * Construct daily indicators
219
+ gen above_100=0 & AQI!=.
220
+ replace above_100=1 if AQI>=100 & AQI!=.
221
+ gen above_200=0 & AQImax!=.
222
+ replace above_200=1 if AQImax>=200 & AQImax!=.
223
+
224
+ * Collapse data to monthly level
225
+ collapse (mean) above_200 pm25api pm10api AQI, by(year month city_id)
226
+
227
+ * Merge with weather data
228
+ merge 1:1 city_id year month using "$data_files/weather_monthly.dta"
229
+ keep if _merge == 3
230
+ drop _merge
231
+
232
+ gen quarter = int((month-1)/3)+1
233
+ collapse (mean) above_200 pm25api pm10api AQI pre tem_mean, by(year quarter city_id)
234
+
235
+ * Construct monthly variables
236
+ egen time=group(year quarter)
237
+ replace pre=. if pre==-9999
238
+
239
+ bysort city_id: egen med_pre=median(pre)
240
+ gen high_pre=0 if pre!=.
241
+ replace high_pre=1 if pre>med_pre & pre!=.
242
+ label var high_pre "\$Rain_{>\tilde{x}}$"
243
+
244
+ gen log_pre=log(pre)
245
+ gen log_api25=log(pm25api)
246
+ gen log_aqi=log(AQI)
247
+ gen log_api10=log(pm10api)
248
+
249
+ gen tem_meand = int(tem_mean)
250
+
251
+ * Monthly pollution regressions
252
+ reghdfe log_api25 high_pre, absorb(time city_id tem_meand) cluster(city_id)
253
+ eststo A
254
+ estadd ysumm, mean
255
+ estadd scalar EN = e(N_full)
256
+ reghdfe log_api10 high_pre, absorb(time city_id tem_meand) cluster(city_id)
257
+ eststo B
258
+ estadd ysumm, mean
259
+ estadd scalar EN = e(N_full)
260
+ reghdfe log_aqi high_pre, absorb(time city_id tem_meand) cluster(city_id)
261
+ eststo C
262
+ estadd ysumm, mean
263
+ estadd scalar EN = e(N_full)
264
+ reghdfe above_200 high_pre if AQI!=., absorb(time city_id tem_meand) cluster(city_id)
265
+ eststo D
266
+ estadd ysumm, mean
267
+ estadd scalar EN = e(N_full)
268
+
269
+ esttab A B C D using "$out_files/TableC6.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() drop(_cons) stats(ymean EN, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
270
+
271
+ **==============================================================================
272
+ * Table C7
273
+ use "$data_files/firm_enf.dta", clear
274
+ drop if revenue == .
275
+ drop if key == .
276
+
277
+ label var min_dist_10 "Mon\$\_{<10km}\$"
278
+ label var any_air "Any Enforcement (0/1)"
279
+ label var post "Post"
280
+ label var key "High Pollution"
281
+
282
+ * Table
283
+ eststo clear
284
+ reghdfe any_air c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
285
+ eststo A
286
+ estadd ysumm, mean
287
+ estadd scalar EN = e(N_full)
288
+ estadd local FirmFE = "Yes"
289
+ estadd local ITFE = "Yes"
290
+ estadd local PTFE = "Yes"
291
+ reghdfe any_water c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
292
+ eststo B
293
+ estadd ysumm, mean
294
+ estadd scalar EN = e(N_full)
295
+ estadd local FirmFE = "Yes"
296
+ estadd local ITFE = "Yes"
297
+ estadd local PTFE = "Yes"
298
+ reghdfe any_waste c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
299
+ eststo C
300
+ estadd ysumm, mean
301
+ estadd scalar EN = e(N_full)
302
+ estadd local FirmFE = "Yes"
303
+ estadd local ITFE = "Yes"
304
+ estadd local PTFE = "Yes"
305
+ reghdfe any_proc c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
306
+ eststo D
307
+ estadd ysumm, mean
308
+ estadd scalar EN = e(N_full)
309
+ estadd local FirmFE = "Yes"
310
+ estadd local ITFE = "Yes"
311
+ estadd local PTFE = "Yes"
312
+ esttab A B C D using "$out_files/TableC7a.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(c.min_dist_10*) stats(ymean EN FirmFE ITFE PTFE, labels("Mean Outcome" "Observations" "Firm FE" "Industry-Time FE" "Province-Time FE")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
313
+
314
+ merge m:1 city_id using "$data_files/Raw/city_info.dta", keepusing(disttocoast)
315
+ keep if _merge == 3
316
+ drop _merge
317
+
318
+ eststo clear
319
+ reghdfe any_air c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
320
+ eststo A
321
+ estadd ysumm, mean
322
+ estadd scalar EN = e(N_full)
323
+ estadd local FirmFE = "Yes"
324
+ estadd local ITFE = "Yes"
325
+ estadd local PTFE = "Yes"
326
+ estadd local DTFE = "No"
327
+ estadd local FCTFE = "No"
328
+ estadd local CTFE = "No"
329
+ reghdfe any_air c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time c.disttocoast#time) cluster(city_id)
330
+ eststo B
331
+ estadd ysumm, mean
332
+ estadd scalar EN = e(N_full)
333
+ estadd local FirmFE = "Yes"
334
+ estadd local ITFE = "Yes"
335
+ estadd local PTFE = "Yes"
336
+ estadd local DTFE = "Yes"
337
+ estadd local FCTFE = "No"
338
+ estadd local CTFE = "No"
339
+ reghdfe any_air c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time c.disttocoast#time c.employment#time) cluster(city_id)
340
+ eststo C
341
+ estadd ysumm, mean
342
+ estadd scalar EN = e(N_full)
343
+ estadd local FirmFE = "Yes"
344
+ estadd local ITFE = "Yes"
345
+ estadd local PTFE = "Yes"
346
+ estadd local DTFE = "Yes"
347
+ estadd local FCTFE = "Yes"
348
+ estadd local CTFE = "No"
349
+ reghdfe any_air c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time city_id#time) cluster(city_id)
350
+ eststo D
351
+ estadd ysumm, mean
352
+ estadd scalar EN = e(N_full)
353
+ estadd local FirmFE = "Yes"
354
+ estadd local ITFE = "Yes"
355
+ estadd local PTFE = "No"
356
+ estadd local DTFE = "No"
357
+ estadd local FCTFE = "Yes"
358
+ estadd local CTFE = "Yes"
359
+ esttab A B C D using "$out_files/TableC7b.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(c.min_dist_10*) stats(ymean EN DTFE FCTFE CTFE FirmFE ITFE PTFE, labels("Mean Outcome" "Observations" "Distance to coast-Time FE" "Firm characteristics-Time FE" "City-Time FE" "Firm FE" "Industry-Time FE" "Province-Time FE" )) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
360
+
361
+ **==============================================================================
362
+ * Table C8
363
+ use "$data_files/Raw/city_info.dta", clear
364
+ merge 1:1 city_id using "$data_files/share.dta"
365
+ drop if _merge == 2
366
+ drop _merge
367
+
368
+ label variable number "\# Monitors"
369
+ label variable number_iv "Min \# Monitors"
370
+
371
+ regress share_rev_10 number, r
372
+ eststo A
373
+ estadd ysumm, mean
374
+ regress share_emp_10 number, r
375
+ eststo B
376
+ estadd ysumm, mean
377
+ regress share_rev_5 number, r
378
+ eststo C
379
+ estadd ysumm, mean
380
+ regress share_emp_5 number, r
381
+ eststo D
382
+ estadd ysumm, mean
383
+ esttab A B C D using "$out_files/TableC8a.tex", replace b(a2) noconstant se(a2) label nolines nogaps compress fragment nonumbers mlabels(none) collabels() drop(_cons) stats(ymean N, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
384
+
385
+ ivregress 2sls share_rev_10 (number = number_iv), r
386
+ eststo A
387
+ estadd ysumm, mean
388
+ ivregress 2sls share_emp_10 (number = number_iv), r
389
+ eststo B
390
+ estadd ysumm, mean
391
+ ivregress 2sls share_rev_5 (number = number_iv), r
392
+ eststo C
393
+ estadd ysumm, mean
394
+ ivregress 2sls share_emp_5 (number = number_iv), r
395
+ eststo D
396
+ estadd ysumm, mean
397
+ esttab A B C D using "$out_files/TableC8b.tex", replace b(a2) noconstant se(a2) label nolines nogaps compress fragment nonumbers mlabels(none) collabels() drop(_cons) stats(ymean N, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
398
+
399
+ **==============================================================================
400
+ * Table C9
401
+ * Robustness: additional controls
402
+ use "$data_files/city_pm.dta", clear
403
+
404
+ label variable post1 "Post"
405
+ label variable number "\# Mon"
406
+ label variable number_iv "Min \# Mon"
407
+
408
+ gen RD_Estimate = c.post1#c.number
409
+
410
+ eststo clear
411
+ reghdfe pm25 RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
412
+ estadd scalar EN = e(N_full)
413
+ eststo A
414
+ ivreghdfe pm25 c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
415
+ estadd scalar EN = e(N_full)
416
+ eststo B
417
+ reghdfe pm25 RD_Estimate i.time#c.area i.time#c.pop, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
418
+ estadd scalar EN = e(N_full)
419
+ eststo C
420
+ ivreghdfe pm25 i.time#c.area i.time#c.pop i.time#c.background (RD_Estimate=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
421
+ estadd scalar EN = e(N_full)
422
+ eststo D
423
+ reghdfe pm25 RD_Estimate i.time#c.area i.time#c.pop i.time#c.background i.time#c.GDP, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
424
+ estadd scalar EN = e(N_full)
425
+ eststo E
426
+ ivreghdfe pm25 i.time#c.area i.time#c.pop i.time#c.background i.time#c.GDP (RD_Estimate=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
427
+ estadd scalar EN = e(N_full)
428
+ eststo F
429
+ esttab A B C D E F using "$out_files/TableC9a.tex", tex keep(RD_Estimate) transform(@/1, pattern(0 0 0 0)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN, labels( "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01)
430
+
431
+ use "$data_files/city_enf.dta", clear
432
+
433
+ label variable post1 "Post"
434
+ label variable number "\# Mon"
435
+ label variable number_iv "Min \# Mon"
436
+
437
+ gen RD_Estimate = c.post1#c.number
438
+
439
+ eststo clear
440
+ reghdfe log_any_air RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
441
+ estadd scalar EN = e(N_full)
442
+ estadd local CFE = "Yes"
443
+ estadd local TTFE = "Yes"
444
+ estadd local CSPost = "Yes"
445
+ estadd local CSTFE = "No"
446
+ estadd local CCTFE = "No"
447
+ estadd local Weather = "Yes"
448
+ eststo A
449
+ ivreghdfe log_any_air c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
450
+ estadd scalar EN = e(N_full)
451
+ estadd local CFE = "Yes"
452
+ estadd local TTFE = "Yes"
453
+ estadd local CSPost = "Yes"
454
+ estadd local CSTFE = "No"
455
+ estadd local CCTFE = "No"
456
+ estadd local Weather = "Yes"
457
+ eststo B
458
+ reghdfe log_any_air RD_Estimate i.time#c.area i.time#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
459
+ estadd scalar EN = e(N_full)
460
+ estadd local CFE = "Yes"
461
+ estadd local TTFE = "Yes"
462
+ estadd local CSPost = "No"
463
+ estadd local CSTFE = "Yes"
464
+ estadd local CCTFE = "No"
465
+ estadd local Weather = "Yes"
466
+ eststo C
467
+ ivreghdfe log_any_air i.time#c.area i.time#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
468
+ estadd scalar EN = e(N_full)
469
+ estadd local CFE = "Yes"
470
+ estadd local TTFE = "Yes"
471
+ estadd local CSPost = "No"
472
+ estadd local CSTFE = "Yes"
473
+ estadd local CCTFE = "No"
474
+ estadd local Weather = "Yes"
475
+ eststo D
476
+ reghdfe log_any_air RD_Estimate i.time#c.area i.time#c.pop i.time#c.background i.time#c.GDP, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
477
+ estadd scalar EN = e(N_full)
478
+ estadd local CFE = "Yes"
479
+ estadd local TTFE = "Yes"
480
+ estadd local CSPost = "No"
481
+ estadd local CSTFE = "Yes"
482
+ estadd local CCTFE = "Yes"
483
+ estadd local Weather = "Yes"
484
+ eststo E
485
+ ivreghdfe log_any_air i.time#c.area i.time#c.pop i.time#c.background i.time#c.GDP (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
486
+ estadd scalar EN = e(N_full)
487
+ estadd local CFE = "Yes"
488
+ estadd local TTFE = "Yes"
489
+ estadd local CSPost = "No"
490
+ estadd local CSTFE = "Yes"
491
+ estadd local CCTFE = "Yes"
492
+ estadd local Weather = "Yes"
493
+ eststo F
494
+ esttab A B C D E F using "$out_files/TableC9b.tex", tex keep(RD_Estimate) transform(@/1, pattern(0 0 0 0)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN CFE TTFE CSPost CSTFE CCTFE Weather, labels("Observations" "City FE" "Target-Time FE" "City size $\times$ Post" "City size-Time FE" "City char.-Time FE" "Weather")) starlevels(* 0.10 ** 0.05 *** 0.01)
495
+
496
+ **==============================================================================
497
+ * Table C10
498
+ * Robustness: Sample Restriction
499
+ use "$data_files/city_pm.dta", clear
500
+
501
+ gen prov_id = int(city_id/100)
502
+ drop if prov_id == 54 | prov_id == 65
503
+
504
+ label variable post1 "Post"
505
+ label variable number "\# Mon"
506
+ label variable number_iv "Min \# Mon"
507
+
508
+ gen RD_Estimate = c.post1#c.number
509
+
510
+ reghdfe pm25 RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
511
+ estadd scalar EN = e(N_full)
512
+ eststo A
513
+ ivreghdfe pm25 c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
514
+ estadd scalar EN = e(N_full)
515
+ eststo B
516
+
517
+ use "$data_files/city_pm_rd.dta", clear
518
+
519
+ gen prov_id = int(city_id/100)
520
+ drop if prov_id == 54 | prov_id == 65
521
+
522
+ gen dist1 = area - 20 if cutoff == 1
523
+ replace dist1 = area - 50 if cutoff == 2
524
+
525
+ gen bench = pm25 if year < 2012
526
+ bys city_id cutoff: egen mean_bench = mean(bench)
527
+
528
+ gen above = dist1 > 0
529
+ gen RD_Estimate = c.post1#c.above
530
+
531
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year month) kernel(uni) vce(cluster city_id)
532
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
533
+ estadd scalar band = e(h_l)
534
+ eststo C
535
+ reghdfe pm25 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
536
+ estadd scalar EN = e(N_full)
537
+ estadd scalar band = 11.3
538
+ eststo D
539
+ esttab A B C D using "$out_files/TableC10a.tex", tex keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN, labels( "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01)
540
+
541
+ use "$data_files/city_enf.dta", clear
542
+
543
+ gen prov_id = int(city_id/100)
544
+ drop if prov_id == 54 | prov_id == 65
545
+
546
+ label variable post1 "Post"
547
+ label variable number "\# Mon"
548
+ label variable number_iv "Min \# Mon"
549
+
550
+ gen RD_Estimate = c.post1#c.number
551
+
552
+ reghdfe log_any_air RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
553
+ estadd scalar EN = e(N_full)
554
+ eststo A
555
+ ivreghdfe log_any_air c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
556
+ estadd scalar EN = e(N_full)
557
+ eststo B
558
+
559
+ use "$data_files/city_enf_rd.dta", clear
560
+
561
+ gen prov_id = int(city_id/100)
562
+ drop if prov_id == 54 | prov_id == 65
563
+
564
+ gen dist1 = area - 20 if cutoff == 1
565
+ replace dist1 = area - 50 if cutoff == 2
566
+
567
+ gen bench = log_any_air if year < 2012
568
+ bys city_id cutoff: egen mean_bench = mean(bench)
569
+
570
+ gen above = dist1 > 0
571
+ gen RD_Estimate = c.post1#c.above
572
+
573
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench) kernel(uni) vce(cluster city_id)
574
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
575
+ estadd scalar band = e(h_l)
576
+ estadd local kern = "Uniform"
577
+ eststo C
578
+ reghdfe log_any_air RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
579
+ estadd scalar EN = e(N_full)
580
+ estadd scalar band = 11.3
581
+ estadd local kern = "Uniform"
582
+ eststo D
583
+ esttab A B C D using "$out_files/TableC10b.tex", tex keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN kern band, labels("Observations" "Kernel" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
584
+
585
+
586
+ **==============================================================================
587
+ * Table C11
588
+ * asif vs all
589
+ use "$data_files/city_enf.dta", clear
590
+
591
+ gen log_any_air_total = log(any_air+any_air_rest+1)
592
+
593
+ label variable post1 "Post"
594
+ label variable number "\# Mon"
595
+ label variable number_iv "Min \# Mon"
596
+
597
+ gen RD_Estimate = c.post1#c.number
598
+
599
+ reghdfe log_any_air_total RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
600
+ estadd scalar EN = e(N_full)
601
+ eststo A
602
+ ivreghdfe log_any_air_total c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
603
+ estadd scalar EN = e(N_full)
604
+ eststo B
605
+
606
+ use "$data_files/city_enf_rd.dta", clear
607
+
608
+ gen log_any_air_total = log(any_air+any_air_rest+1)
609
+
610
+ gen dist1 = area - 20 if cutoff == 1
611
+ replace dist1 = area - 50 if cutoff == 2
612
+
613
+ gen bench = log_any_air_total if year < 2012
614
+ bys city_id cutoff: egen mean_bench = mean(bench)
615
+
616
+ gen above = dist1 > 0
617
+ gen RD_Estimate = c.post1#c.above
618
+
619
+ rdrobust log_any_air_total dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year quarter) kernel(uni) vce(cluster city_id)
620
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
621
+ estadd scalar band = e(h_l)
622
+ eststo C
623
+ reghdfe log_any_air_total RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
624
+ estadd scalar EN = e(N_full)
625
+ estadd scalar band = 11.3
626
+ eststo D
627
+ esttab A B C D using "$out_files/TableC11a.tex", tex keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN, labels("Observations")) starlevels(* 0.10 ** 0.05 *** 0.01)
628
+
629
+
630
+ use "$data_files/city_enf.dta", clear
631
+
632
+ gen log_any_air_rest = log(any_air_rest+1)
633
+
634
+ label variable post1 "Post"
635
+ label variable number "\# Mon"
636
+ label variable number_iv "Min \# Mon"
637
+
638
+ gen RD_Estimate = c.post1#c.number
639
+
640
+ reghdfe log_any_air_rest RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
641
+ estadd scalar EN = e(N_full)
642
+ eststo A
643
+ ivreghdfe log_any_air_rest c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
644
+ estadd scalar EN = e(N_full)
645
+ eststo B
646
+
647
+ use "$data_files/city_enf_rd.dta", clear
648
+
649
+ gen log_any_air_rest = log(any_air_rest+1)
650
+
651
+ gen dist1 = area - 20 if cutoff == 1
652
+ replace dist1 = area - 50 if cutoff == 2
653
+
654
+ gen bench = log_any_air_rest if year < 2012
655
+ bys city_id cutoff: egen mean_bench = mean(bench)
656
+
657
+ gen above = dist1 > 0
658
+ gen RD_Estimate = c.post1#c.above
659
+
660
+ rdrobust log_any_air_rest dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year quarter) kernel(uni) vce(cluster city_id)
661
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
662
+ estadd scalar band = e(h_l)
663
+ eststo C
664
+ reghdfe log_any_air_rest RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
665
+ estadd scalar EN = e(N_full)
666
+ estadd scalar band = 11.3
667
+ eststo D
668
+ esttab A B C D using "$out_files/TableC11b.tex", tex keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN, labels("Observations")) starlevels(* 0.10 ** 0.05 *** 0.01)
669
+
670
+
671
+ **==============================================================================
672
+ * Table C12
673
+ * kernel and covs
674
+ use "$data_files/city_pm_rd.dta", clear
675
+
676
+ gen dist1 = area - 20 if cutoff == 1
677
+ replace dist1 = area - 50 if cutoff == 2
678
+
679
+ gen bench = pm25 if year < 2012
680
+ bys city_id: egen mean_bench = mean(bench)
681
+
682
+ eststo clear
683
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year month) kernel(uni) vce(cluster city_id)
684
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
685
+ estadd scalar band = e(h_l)
686
+ eststo A
687
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) covs(cutoff mean_bench year month) kernel(tri) vce(cluster city_id)
688
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
689
+ estadd scalar band = e(h_l)
690
+ eststo B
691
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) covs(cutoff mean_bench year month) kernel(epa) vce(cluster city_id)
692
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
693
+ estadd scalar band = e(h_l)
694
+ eststo C
695
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) covs() kernel(uni) vce(cluster city_id)
696
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
697
+ estadd scalar band = e(h_l)
698
+ eststo D
699
+ esttab A B C D using "$out_files/TableC12a1.tex", tex keep(RD_Estimate) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN band, labels("Observations" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
700
+
701
+ eststo clear
702
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) covs(cutoff) kernel(uni) vce(cluster city_id)
703
+ eststo A
704
+ rdrobust number dist1 if year>=2015, p(1) h(12.3) covs(cutoff) kernel(tri) vce(cluster city_id)
705
+ eststo B
706
+ rdrobust number dist1 if year>=2015, p(1) h(12.5) covs(cutoff) kernel(epa) vce(cluster city_id)
707
+ eststo C
708
+ rdrobust number dist1 if year>=2015, p(1) h(13.8) covs() kernel(uni) vce(cluster city_id)
709
+ eststo D
710
+ esttab A B C D using "$out_files/TableC12a2.tex", tex replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers noobs mlabels(none) keep(RD_Estimate) coeflabels(RD_Estimate "First stage") starlevels(* 0.10 ** 0.05 *** 0.01)
711
+
712
+ use "$data_files/city_enf_rd.dta", clear
713
+
714
+ gen dist1 = area - 20 if cutoff == 1
715
+ replace dist1 = area - 50 if cutoff == 2
716
+
717
+ gen dist2 = pop - 25 if cutoff == 1
718
+ replace dist2 = pop - 50 if cutoff == 2
719
+
720
+ gen bench = log_any_air if year < 2012
721
+ bys city_id: egen mean_bench = mean(bench)
722
+
723
+ gen above = dist1 > 0
724
+ gen RD_Estimate = c.post1#c.above
725
+
726
+ eststo clear
727
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year quarter) kernel(uni) vce(cluster city_id)
728
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
729
+ estadd scalar band = e(h_l)
730
+ eststo A
731
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) covs(cutoff mean_bench year quarter) kernel(tri) vce(cluster city_id)
732
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
733
+ estadd scalar band = e(h_l)
734
+ eststo B
735
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) covs(cutoff mean_bench year quarter) kernel(epa) vce(cluster city_id)
736
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
737
+ estadd scalar band = e(h_l)
738
+ eststo C
739
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) covs() kernel(uni) vce(cluster city_id)
740
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
741
+ estadd scalar band = e(h_l)
742
+ eststo D
743
+ esttab A B C D using "$out_files/TableC12b1.tex", tex keep(RD_Estimate) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN band, labels("Observations" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
744
+
745
+ eststo clear
746
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) covs(cutoff) kernel(uni) vce(cluster city_id)
747
+ eststo A
748
+ estadd local kern = "Uniform"
749
+ estadd local cov = "Yes"
750
+ rdrobust number dist1 if year>=2015, p(1) h(13.1) covs(cutoff) kernel(tri) vce(cluster city_id)
751
+ eststo B
752
+ estadd local kern = "Epanechnikov"
753
+ estadd local cov = "Yes"
754
+ rdrobust number dist1 if year>=2015, p(1) h(12.5) covs(cutoff) kernel(epa) vce(cluster city_id)
755
+ eststo C
756
+ estadd local kern = "Triangle"
757
+ estadd local cov = "Yes"
758
+ rdrobust number dist1 if year>=2015, p(1) h(11.4) covs() kernel(uni) vce(cluster city_id)
759
+ eststo D
760
+ estadd local kern = "Uniform"
761
+ estadd local cov = "No"
762
+ esttab A B C D using "$out_files/TableC12b2.tex", tex replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers noobs mlabels(none) keep(RD_Estimate) coeflabels(RD_Estimate "First stage") stats(kern cov, labels("Kernel" "Covariates")) starlevels(* 0.10 ** 0.05 *** 0.01)
763
+
764
+
765
+ **==============================================================================
766
+ * Table C13
767
+ * Cutoff 1
768
+ use "$data_files/city_pm.dta", clear
769
+
770
+ gen dist1 = area - 20
771
+
772
+ gen bench = pm25 if year < 2012
773
+ bys city_id: egen mean_bench = mean(bench)
774
+
775
+ gen above = dist1 > 0
776
+ gen RD_Estimate = c.post1#c.above
777
+
778
+ eststo clear
779
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(mean_bench year quarter) kernel(uni) vce(cluster city_id)
780
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
781
+ estadd scalar band = e(h_l)
782
+ eststo A
783
+ reghdfe pm25 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 if abs(dist1) < 11.3, a(year#month) cl(city_id)
784
+ estadd scalar EN = e(N_full)
785
+ estadd scalar band = 11.3
786
+ eststo B
787
+
788
+ use "$data_files/city_enf.dta", clear
789
+
790
+ gen dist1 = area - 20
791
+
792
+ gen bench = log_any_air if year < 2012
793
+ bys city_id: egen mean_bench = mean(bench)
794
+
795
+ gen above = dist1 > 0
796
+ gen RD_Estimate = c.post1#c.above
797
+
798
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(mean_bench year quarter) kernel(uni) vce(cluster city_id)
799
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
800
+ estadd scalar band = e(h_l)
801
+ eststo C
802
+ reghdfe log_any_air RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 if abs(dist1) < 11.3, a(time) cl(city_id)
803
+ estadd scalar EN = e(N_full)
804
+ estadd scalar band = 11.3
805
+ eststo D
806
+ esttab A B C D using "$out_files/TableC13a1.tex", tex keep(RD_Estimate) transform(@/0.79 1/0.79, pattern(0 1 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN band, labels("Observations" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
807
+
808
+ eststo clear
809
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) kernel(uni) vce(cluster city_id)
810
+ eststo A
811
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) kernel(uni) vce(cluster city_id)
812
+ eststo B
813
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) kernel(uni) vce(cluster city_id)
814
+ eststo C
815
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) covs() kernel(uni) vce(cluster city_id)
816
+ eststo D
817
+ esttab A B C D using "$out_files/TableC13a2.tex", tex replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers noobs mlabels(none) keep(RD_Estimate) coeflabels(RD_Estimate "First stage") starlevels(* 0.10 ** 0.05 *** 0.01)
818
+
819
+ * Cutoff 2
820
+ use "$data_files/city_pm.dta", clear
821
+
822
+ gen dist1 = area - 50
823
+
824
+ gen bench = pm25 if year < 2012
825
+ bys city_id: egen mean_bench = mean(bench)
826
+
827
+ gen above = dist1 > 0
828
+ gen RD_Estimate = c.post1#c.above
829
+
830
+ eststo clear
831
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(mean_bench year month) kernel(uni) vce(cluster city_id)
832
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
833
+ estadd scalar band = e(h_l)
834
+ eststo A
835
+ reghdfe pm25 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 if abs(dist1) < 11.3, a(time) cl(city_id)
836
+ estadd scalar EN = e(N_full)
837
+ estadd scalar band = 11.3
838
+ eststo B
839
+
840
+ use "$data_files/city_enf.dta", clear
841
+
842
+ gen dist1 = area - 50
843
+
844
+ gen bench = log_any_air if year < 2012
845
+ bys city_id: egen mean_bench = mean(bench)
846
+
847
+ gen above = dist1 > 0
848
+ gen RD_Estimate = c.post1#c.above
849
+
850
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(mean_bench year quarter) kernel(uni) vce(cluster city_id)
851
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
852
+ estadd scalar band = e(h_l)
853
+ eststo C
854
+ reghdfe log_any_air RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 if abs(dist1) < 11.3, a(time) cl(city_id)
855
+ estadd scalar EN = e(N_full)
856
+ estadd scalar band = 11.3
857
+ eststo D
858
+ esttab A B C D using "$out_files/TableC13b1.tex", tex keep(RD_Estimate) transform(@/1.76 1/1.76, pattern(0 1 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN band, labels("Observations" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
859
+
860
+ eststo clear
861
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) kernel(uni) vce(cluster city_id)
862
+ eststo A
863
+ estadd local kern = "Uniform"
864
+ estadd scalar band = 11.3
865
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) kernel(uni) vce(cluster city_id)
866
+ eststo B
867
+ estadd local kern = "Uniform"
868
+ estadd scalar band = 11.3
869
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) kernel(uni) vce(cluster city_id)
870
+ eststo C
871
+ estadd local kern = "Uniform"
872
+ estadd scalar band = 11.3
873
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) covs() kernel(uni) vce(cluster city_id)
874
+ eststo D
875
+ estadd local kern = "Uniform"
876
+ estadd local band = 11.3
877
+ esttab A B C D using "$out_files/TableC13b2.tex", tex replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers noobs mlabels(none) keep(RD_Estimate) coeflabels(RD_Estimate "First stage") stats(kern band, labels("Kernel" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
878
+
879
+
880
+ **==============================================================================
881
+ * Table C14
882
+ * Spillover in aod
883
+ use "$data_files/city_pm_rd.dta", clear
884
+
885
+ rename pm pm_monitor
886
+ drop if pm_monitor == .
887
+ drop if pm_direct == .
888
+ drop if pm_indirect == .
889
+
890
+ gen dist1 = area - 20 if cutoff == 1
891
+ replace dist1 = area - 50 if cutoff == 2
892
+
893
+ gen bench_monitor = pm_monitor if year < 2012
894
+ bys city_id cutoff: egen mean_bench_monitor = mean(bench_monitor)
895
+
896
+ gen RD_Estimate = .
897
+ gen above = dist1 > 0
898
+
899
+ replace RD_Estimate = c.post1#c.number
900
+ eststo clear
901
+ reghdfe pm_monitor RD_Estimate c.post1#c.area c.post1#c.pop if cutoff == 1, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
902
+ eststo A
903
+ summ pm_monitor
904
+ estadd scalar ysumm = r(mean)
905
+ estadd scalar EN = e(N_full)
906
+ ivreghdfe pm_monitor c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv) if cutoff == 1, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
907
+ eststo B
908
+ summ pm_monitor
909
+ estadd scalar ysumm = r(mean)
910
+ estadd scalar EN = e(N_full)
911
+ rdrobust pm_monitor dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench_monitor year month) kernel(uni) vce(cluster city_id)
912
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
913
+ summ pm_monitor if abs(dist1)<11.3
914
+ estadd scalar ysumm = r(mean)
915
+ eststo C
916
+ replace RD_Estimate = c.post1#c.above
917
+ reghdfe pm_monitor RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
918
+ estadd scalar EN = e(N)
919
+ summ pm_monitor if abs(dist1)<11.3
920
+ estadd scalar ysumm = r(mean)
921
+ eststo D
922
+ esttab A B C D using "$out_files/TableC14a.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN ysumm, labels("Observations" "Mean Outcome")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
923
+
924
+ use "$data_files/city_pm_rd.dta", clear
925
+
926
+ rename pm pm_monitor
927
+ drop if pm_monitor == .
928
+ drop if pm_direct == .
929
+ drop if pm_indirect == .
930
+
931
+ gen dist1 = area - 20 if cutoff == 1
932
+ replace dist1 = area - 50 if cutoff == 2
933
+
934
+ gen bench_dir = pm_direct if year < 2012
935
+ bys city_id cutoff: egen mean_bench_dir = mean(bench_dir)
936
+
937
+ gen bench_in = pm_indirect if year < 2012
938
+ bys city_id cutoff: egen mean_bench_in = mean(bench_in)
939
+
940
+ gen RD_Estimate = .
941
+ gen above = dist1 > 0
942
+
943
+ replace RD_Estimate = c.post1#c.number
944
+ eststo clear
945
+ reghdfe pm_direct RD_Estimate c.post1#c.area c.post1#c.pop if cutoff == 1, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
946
+ eststo A
947
+ summ pm_direct
948
+ estadd scalar ysumm = r(mean)
949
+ estadd scalar EN = e(N_full)
950
+ ivreghdfe pm_direct c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv) if cutoff == 1, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
951
+ eststo B
952
+ summ pm_direct
953
+ estadd scalar ysumm = r(mean)
954
+ estadd scalar EN = e(N_full)
955
+ rdrobust pm_direct dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench_dir year month) kernel(uni) vce(cluster city_id)
956
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
957
+ summ pm_direct if abs(dist1) < 11.3
958
+ estadd scalar ysumm = r(mean)
959
+ eststo C
960
+ replace RD_Estimate = c.post1#c.above
961
+ reghdfe pm_direct RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
962
+ estadd scalar EN = e(N)
963
+ summ pm_direct if abs(dist1) < 11.3
964
+ estadd scalar ysumm = r(mean)
965
+ eststo D
966
+ esttab A B C D using "$out_files/TableC14b.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN ysumm, labels("Observations" "Mean Outcome")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
967
+
968
+ replace RD_Estimate = c.post1#c.number
969
+ eststo clear
970
+ reghdfe pm_indirect RD_Estimate c.post1#c.area c.post1#c.pop if cutoff == 1, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
971
+ eststo A
972
+ summ pm_indirect
973
+ estadd scalar ysumm = r(mean)
974
+ estadd scalar EN = e(N_full)
975
+ ivreghdfe pm_indirect c.post1#c.area c.post1#c.pop pre tem_mean (RD_Estimate=c.post1#c.number_iv) if cutoff == 1, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
976
+ eststo B
977
+ summ pm_indirect
978
+ estadd scalar ysumm = r(mean)
979
+ estadd scalar EN = e(N_full)
980
+ rdrobust pm_indirect dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench_in year month) kernel(uni) vce(cluster city_id)
981
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
982
+ summ pm_indirect if abs(dist1) < 11.3
983
+ estadd scalar ysumm = r(mean)
984
+ eststo C
985
+ replace RD_Estimate = c.post1#c.above
986
+ reghdfe pm_indirect RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
987
+ summ pm_indirect if abs(dist1) < 11.3
988
+ estadd scalar ysumm = r(mean)
989
+ estadd scalar EN = e(N)
990
+ eststo D
991
+ esttab A B C D using "$out_files/TableC14c.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN ysumm, labels("Observations" "Mean Outcome")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
992
+
993
+ * Spillover in enf
994
+ use "$data_files/city_enf.dta", clear
995
+
996
+ label variable post1 "Post"
997
+ label variable number "\# Mon"
998
+ label variable number_iv "Min \# Mon"
999
+
1000
+ gen RD_Estimate = c.post1#c.number
1001
+
1002
+ eststo clear
1003
+ reghdfe log_any_air_10 RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1004
+ summ log_any_air_10
1005
+ estadd scalar ysumm = r(mean)
1006
+ estadd scalar EN = e(N_full)
1007
+ eststo A
1008
+ ivreghdfe log_any_air_10 c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1009
+ summ log_any_air_10
1010
+ estadd scalar ysumm = r(mean)
1011
+ estadd scalar EN = e(N_full)
1012
+ eststo B
1013
+
1014
+ use "$data_files/city_enf_rd.dta", clear
1015
+
1016
+ gen dist1 = area - 20 if cutoff == 1
1017
+ replace dist1 = area - 50 if cutoff == 2
1018
+
1019
+ gen bench_10 = log_any_air_10 if year < 2012
1020
+ bys city_id cutoff: egen mean_bench_10 = mean(bench_10)
1021
+
1022
+ gen above = dist1 > 0
1023
+ gen RD_Estimate = c.post1#c.above
1024
+
1025
+ rdrobust log_any_air_10 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench_10 year quarter) kernel(uni) vce(cluster city_id)
1026
+ summ log_any_air_10 if abs(dist1)<11.3
1027
+ estadd scalar ysumm = r(mean)
1028
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
1029
+ estadd scalar band = e(h_l)
1030
+ eststo C
1031
+ reghdfe log_any_air_10 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
1032
+ summ log_any_air_10 if abs(dist1)<11.3
1033
+ estadd scalar ysumm = r(mean)
1034
+ estadd scalar EN = e(N)
1035
+ estadd scalar band = 11.3
1036
+ eststo D
1037
+ esttab A B C D using "$out_files/TableC14d.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN ysumm, labels("Observations" "Mean Outcome")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
1038
+
1039
+
1040
+ use "$data_files/city_enf.dta", clear
1041
+
1042
+ label variable post1 "Post"
1043
+ label variable number "\# Mon"
1044
+ label variable number_iv "Min \# Mon"
1045
+
1046
+ gen RD_Estimate = c.post1#c.number
1047
+
1048
+ eststo clear
1049
+ reghdfe log_any_air_20 RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1050
+ summ log_any_air_20
1051
+ estadd scalar ysumm = r(mean)
1052
+ estadd scalar EN = e(N_full)
1053
+ eststo A
1054
+ ivreghdfe log_any_air_20 c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1055
+ summ log_any_air_20
1056
+ estadd scalar ysumm = r(mean)
1057
+ estadd scalar EN = e(N_full)
1058
+ eststo B
1059
+
1060
+ use "$data_files/city_enf_rd.dta", clear
1061
+
1062
+ gen dist1 = area - 20 if cutoff == 1
1063
+ replace dist1 = area - 50 if cutoff == 2
1064
+
1065
+ gen bench_20 = log_any_air_20 if year < 2012
1066
+ bys city_id cutoff: egen mean_bench_20 = mean(bench_20)
1067
+
1068
+ gen above = dist1 > 0
1069
+ gen RD_Estimate = c.post1#c.above
1070
+
1071
+ rdrobust log_any_air_20 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench_20 year quarter) kernel(uni) vce(cluster city_id)
1072
+ summ log_any_air_20 if abs(dist1)<11.3
1073
+ estadd scalar ysumm = r(mean)
1074
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
1075
+ estadd scalar band = e(h_l)
1076
+ eststo C
1077
+ reghdfe log_any_air_20 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
1078
+ summ log_any_air_20 if abs(dist1)<11.3
1079
+ estadd scalar ysumm = r(mean)
1080
+ estadd scalar EN = e(N)
1081
+ estadd scalar band = 11.3
1082
+ eststo D
1083
+ esttab A B C D using "$out_files/TableC14e.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN ysumm, labels("Observations" "Mean Outcome")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
1084
+
1085
+ use "$data_files/city_enf.dta", clear
1086
+
1087
+ label variable post1 "Post"
1088
+ label variable number "\# Mon"
1089
+ label variable number_iv "Min \# Mon"
1090
+
1091
+ gen RD_Estimate = c.post1#c.number
1092
+
1093
+ eststo clear
1094
+ reghdfe log_any_air_50 RD_Estimate c.post1#c.area c.post1#c.pop, a(city_id pred tem_meand age_year incentive2#time) cluster(city_id)
1095
+ summ log_any_air_50
1096
+ estadd scalar ysumm = r(mean)
1097
+ estadd scalar EN = e(N_full)
1098
+ eststo A
1099
+ ivreghdfe log_any_air_50 c.post1#c.area c.post1#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id pred tem_meand age_year incentive2#time) cluster(city_id)
1100
+ summ log_any_air_50
1101
+ estadd scalar ysumm = r(mean)
1102
+ estadd scalar EN = e(N_full)
1103
+ eststo B
1104
+
1105
+ use "$data_files/city_enf_rd.dta", clear
1106
+
1107
+ gen dist1 = area - 20 if cutoff == 1
1108
+ replace dist1 = area - 50 if cutoff == 2
1109
+
1110
+ gen bench_50 = log_any_air_50 if year < 2012
1111
+ bys city_id cutoff: egen mean_bench_50 = mean(bench_50)
1112
+
1113
+ gen above = dist1 > 0
1114
+ gen RD_Estimate = c.post1#c.above
1115
+
1116
+ rdrobust log_any_air_50 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench_50 year quarter) kernel(uni) vce(cluster city_id)
1117
+ summ log_any_air_50 if abs(dist1)<11.3
1118
+ estadd scalar ysumm = r(mean)
1119
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
1120
+ estadd local kern = "Uniform"
1121
+ estadd scalar band = 11.3
1122
+ eststo C
1123
+ reghdfe log_any_air_50 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
1124
+ summ log_any_air_50 if abs(dist1)<11.3
1125
+ estadd scalar ysumm = r(mean)
1126
+ estadd scalar EN = e(N)
1127
+ estadd local kern = "Uniform"
1128
+ estadd scalar band = 11.3
1129
+ eststo D
1130
+ esttab A B C D using "$out_files/TableC14f.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN ysumm kern band, labels("Observations" "Mean Outcome" "Kernel" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
1131
+
1132
+
1133
+ **==============================================================================
1134
+ * Table C15
1135
+ * Promotion
1136
+ use "$data_files/city_pm.dta", clear
1137
+
1138
+ label variable post1 "Post"
1139
+ label variable number "\# Mon"
1140
+ label variable number_iv "Min \# Mon"
1141
+
1142
+ gen above57 = age<=57
1143
+ gen RD_Estimate = c.post1#c.number
1144
+ label variable above57 "Below 58"
1145
+
1146
+ eststo clear
1147
+ reghdfe pm25 RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1148
+ eststo A
1149
+ estadd ysumm, mean
1150
+ estadd scalar EN = e(N_full)
1151
+ reghdfe pm25 RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57 if age >= 51 & age <= 62, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1152
+ eststo B
1153
+ estadd ysumm, mean
1154
+ estadd scalar EN = e(N_full)
1155
+ reghdfe pm25 RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57 if age >= 53 & age <= 62, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1156
+ eststo C
1157
+ estadd ysumm, mean
1158
+ estadd scalar EN = e(N_full)
1159
+ reghdfe pm25 RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57 if age >= 55 & age <= 60, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1160
+ eststo D
1161
+ estadd ysumm, mean
1162
+ estadd scalar EN = e(N_full)
1163
+ esttab A B C D using "$out_files/TableC15a.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(RD_Estimate c.RD_Estimate#c.above57) coeflabels(RD_Estimate "\# Monitors" c.RD_Estimate#c.above57 "\# Monitors $\times$ Below 58") stats(ymean EN, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
1164
+
1165
+ use "$data_files/city_enf.dta", clear
1166
+
1167
+ label variable post1 "Post"
1168
+ label variable number "\# Mon"
1169
+ label variable number_iv "Min \# Mon"
1170
+
1171
+ gen above57 = age <= 57
1172
+ gen RD_Estimate = c.post1#c.number
1173
+ label variable above57 "Below 58"
1174
+
1175
+ eststo clear
1176
+ reghdfe log_any_air RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1177
+ eststo A
1178
+ estadd ysumm, mean
1179
+ estadd scalar EN = e(N_full)
1180
+ reghdfe log_any_air RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57 if age >= 51 & age <= 62, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1181
+ eststo B
1182
+ estadd ysumm, mean
1183
+ estadd scalar EN = e(N_full)
1184
+ reghdfe log_any_air RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57 if age >= 53 & age <= 62, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1185
+ eststo C
1186
+ estadd ysumm, mean
1187
+ estadd scalar EN = e(N_full)
1188
+ reghdfe log_any_air RD_Estimate c.post1#c.area c.post1#c.pop c.RD_Estimate#c.above57 if age >= 55 & age <= 60, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
1189
+ eststo D
1190
+ estadd ysumm, mean
1191
+ estadd scalar EN = e(N_full)
1192
+ esttab A B C D using "$out_files/TableC15b.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(RD_Estimate c.RD_Estimate#c.above57) coeflabels(RD_Estimate "\# Monitors" c.RD_Estimate#c.above57 "\# Monitors $\times$ Below 58") stats(ymean EN, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
1193
+
1194
+
1195
+ **==============================================================================
1196
+ * Table C16
1197
+ * Balance
1198
+ use "$data_files/city_pm.dta", clear
1199
+ keep if year < 2015
1200
+
1201
+ replace light = log(light)
1202
+ gen log_any_air = log(any_air+1)
1203
+
1204
+ collapse (mean) pm25 light log_any_air number area pop age city_id, by(city_cn)
1205
+ gen above57 = age > 57
1206
+
1207
+ label variable number "\# Monitors"
1208
+ label variable area "Size of buildup area"
1209
+ label variable pop "Urban population"
1210
+ label variable pm25 "AOD before 2015"
1211
+ label variable light "Night light before 2015"
1212
+ label variable log_any_air "log(\# Firms) before 2015"
1213
+
1214
+ regress above57 number area pop pm25 light log_any_air
1215
+ test number area pop pm25 light log_any_air
1216
+ regress above57 number area pop pm25 light log_any_air if age >= 51 & age <= 62
1217
+ test number area pop pm25 light log_any_air
1218
+ regress above57 number area pop pm25 light log_any_air if age >= 53 & age <= 62
1219
+ test number area pop pm25 light log_any_air
1220
+ regress above57 number area pop pm25 light log_any_air if age >= 55 & age <= 60
1221
+ test number area pop pm25 light log_any_air
1222
+
1223
+ eststo clear
1224
+ eststo tot: estpost summarize number area pop pm25 light log_any_air
1225
+ eststo treat1: estpost summarize number area pop pm25 light log_any_air if above57==1
1226
+ eststo control1: estpost summarize number area pop pm25 light log_any_air if above57==0
1227
+ eststo diff1: estpost ttest number area pop pm25 light log_any_air, by(above57)
1228
+ eststo diff1: estadd scalar pvalue = 0.19
1229
+ eststo diff2: estpost ttest number area pop pm25 light log_any_air if age >= 51 & age <= 62, by(above57)
1230
+ eststo diff2: estadd scalar pvalue = 0.15
1231
+ eststo diff3: estpost ttest number area pop pm25 light log_any_air if age >= 53 & age <= 62, by(above57)
1232
+ eststo diff3: estadd scalar pvalue = 0.29
1233
+ eststo diff4: estpost ttest number area pop pm25 light log_any_air if age >= 55 & age <= 60, by(above57)
1234
+ eststo diff4: estadd scalar pvalue = 0.37
1235
+ esttab tot treat1 control1 diff1 diff2 diff3 diff4 using "$out_files/TableC16.tex", tex label noconstant nolines nogaps compress fragment nonumbers mlabels(,none) collabels(,none) cells(mean(pattern(1 1 1 0 0 0 0) fmt(a2)) & b(star pattern(0 0 0 1 1 1 1) fmt(a2)) sd(pattern(1 1 1 0 0 0 0) fmt(a2) par) & se(pattern(0 0 0 1 1 1 1) fmt(a2) par)) stats(N pvalue, labels("Observations" "Joint Test (p-value)")) starlevels(* 0.10 ** 0.05 *** 0.01) replace
1236
+
1237
+
1238
+ **==============================================================================
1239
+ * Table C17
1240
+
1241
+ use "$data_files/city_pm.dta", clear
1242
+ label variable post1 "Post"
1243
+ label variable number "\# Mon"
1244
+ label variable number_iv "Min \# Mon"
1245
+
1246
+ merge 1:1 city_cn year month using "$data_files/Raw/baidu.dta"
1247
+ keep if _merge == 3
1248
+ drop _merge
1249
+
1250
+ replace sear_freq_w1 = sear_freq_w1/pop
1251
+ replace sear_freq_w2 = sear_freq_w2/pop
1252
+ replace sear_freq_w3 = sear_freq_w3/pop
1253
+ replace sear_freq_w4 = sear_freq_w4/pop
1254
+ replace sear_freq_w5 = sear_freq_w5/pop
1255
+
1256
+ foreach x of varlist sear_freq_w* {
1257
+ egen m_`x' = mean(`x')
1258
+ egen sd_`x' = sd(`x')
1259
+ gen std_`x' = (`x'- m_`x')/sd_`x'
1260
+ }
1261
+
1262
+ forvalues i=1/5 {
1263
+ replace sear_freq_w`i'=0 if sear_freq_w`i'==.
1264
+ gen log_w`i'=log(sear_freq_w`i'+1)
1265
+ gen any_w`i'=0
1266
+ replace any_w`i'=1 if sear_freq_w`i'>0 & sear_freq_w`i'!=.
1267
+ }
1268
+
1269
+ eststo clear
1270
+ ivreghdfe log_w1 i.time#c.area i.time#c.pop (c.post1#c.number=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1271
+ eststo A
1272
+ summ log_w1
1273
+ estadd scalar ymean = r(mean)
1274
+ ivreghdfe log_w2 i.time#c.area i.time#c.pop (c.post1#c.number=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1275
+ eststo B
1276
+ summ log_w2
1277
+ estadd scalar ymean = r(mean)
1278
+ ivreghdfe log_w3 i.time#c.area i.time#c.pop (c.post1#c.number=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1279
+ eststo C
1280
+ summ log_w3
1281
+ estadd scalar ymean = r(mean)
1282
+ ivreghdfe log_w4 i.time#c.area i.time#c.pop (c.post1#c.number=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1283
+ eststo D
1284
+ summ log_w4
1285
+ estadd scalar ymean = r(mean)
1286
+ ivreghdfe log_w5 i.time#c.area i.time#c.pop (c.post1#c.number=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
1287
+ eststo E
1288
+ summ log_w5
1289
+ estadd scalar ymean = r(mean)
1290
+ estfe A B C D E, labels(city_id "City FE" time "Time FE")
1291
+ return list
1292
+ esttab A B C D E using "$out_files/TableC17.tex", replace b(a2) se(a2) keep(c.post1#c.number) coeflabels(c.post1#c.number "\# Monitors") label noconstant nolines nogaps compress fragment nonumbers mlabels(none) collabels() stats(ymean N, labels( "Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01)
1293
+
1294
+
1295
+ **==============================================================================
1296
+ ** Figures
1297
+
1298
+ **==============================================================================
1299
+ * Figure D3
1300
+ use "$data_files/firm_enf.dta", clear
1301
+
1302
+ fvset base 4 min_d_d4
1303
+
1304
+ reghdfe any_air i.post##i.min_d_d4 if min_dist<50 & starty<=2010, absorb(id time industry#time prov_id#time) cluster(city_id) poolsize(1) compact
1305
+ coefplot, baselevels omitted vert yline(0, lc(cranberry)) keep(1.post1#*) coeflabels(1.post1#0.min_d_d4 = "0-5km" 1.post1#1.min_d_d4 = "5-10km" 1.post1#2.min_d_d4 = "10-15km" 1.post1#3.min_d_d4 = "15-20km" 1.post1#4.min_d_d4 = "20-50km") drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle() le(95)
1306
+ graph export "$out_files/any_air_gradient_50_ci.pdf", replace
1307
+
1308
+
1309
+ **==============================================================================
1310
+ * Figure D5
1311
+ use "$data_files/firm_enf.dta", clear
1312
+
1313
+ merge m:1 city_id using "$data_files/Raw/city_info.dta", keepusing(env_lat env_lon centroid_lat centroid_lon)
1314
+ keep if _merge == 3
1315
+ drop _merge
1316
+
1317
+ geodist env_lat env_lon lat lon, gen(env_dist)
1318
+ gen min_env_d4 = int(env_dist/5)
1319
+ replace min_env_d4 = 4 if min_env_d4 > 4
1320
+
1321
+ * set base level
1322
+ fvset base 20 time
1323
+ fvset base 4 min_env_d4
1324
+
1325
+ geodist centroid_lat centroid_lon lat lon, gen(cen_dist)
1326
+ gen min_cen_d4 = int(cen_dist/5)
1327
+ replace min_cen_d4 = 4 if min_cen_d4 > 4
1328
+
1329
+ * set base level
1330
+ fvset base 20 time
1331
+ fvset base 4 min_cen_d4
1332
+
1333
+ reghdfe any_air i.time##i.min_env_d4 i.post##i.min_d_d4 i.post##i.min_cen_d4 if env_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id) poolsize(1) compact
1334
+
1335
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#0.min_env_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_5_) replace
1336
+
1337
+ twoway (rarea enf_5_ul1 enf_5_ll1 enf_5_at, color(gs6%20)) (scatter enf_5_b enf_5_at, msymbol(p) mc(black%60)) (line enf_5_b enf_5_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1338
+ graph export "$out_files/any_air_env_event_5.pdf", replace
1339
+
1340
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#1.min_env_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_10_) replace
1341
+
1342
+ twoway (rarea enf_10_ul1 enf_10_ll1 enf_10_at, color(gs6%20)) (scatter enf_10_b enf_10_at, msymbol(p) mc(black%60)) (line enf_10_b enf_10_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1343
+ graph export "$out_files/any_air_env_event_10.pdf", replace
1344
+
1345
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#2.min_env_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_15_) replace
1346
+
1347
+ twoway (rarea enf_15_ul1 enf_15_ll1 enf_15_at, color(gs6%20)) (scatter enf_15_b enf_10_at, msymbol(p) mc(black%60)) (line enf_15_b enf_15_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1348
+ graph export "$out_files/any_air_env_event_15.pdf", replace
1349
+
1350
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#3.min_env_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_20_) replace
1351
+
1352
+ twoway (rarea enf_20_ul1 enf_20_ll1 enf_20_at, color(gs6%20)) (scatter enf_20_b enf_20_at, msymbol(p) mc(black%60)) (line enf_20_b enf_20_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1353
+ graph export "$out_files/any_air_env_event_20.pdf", replace
1354
+
1355
+
1356
+
1357
+ reghdfe any_air i.time##i.min_cen_d4 i.post##i.min_d_d4 i.post##i.min_env_d4 if cen_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id) poolsize(1) compact
1358
+
1359
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#0.min_cen_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_5_) replace
1360
+
1361
+ twoway (rarea enf_5_ul1 enf_5_ll1 enf_5_at, color(gs6%20)) (scatter enf_5_b enf_5_at, msymbol(p) mc(black%60)) (line enf_5_b enf_5_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1362
+ graph export "$out_files/any_air_cen_event_5.pdf", replace
1363
+
1364
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#1.min_cen_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_10_) replace
1365
+
1366
+ twoway (rarea enf_10_ul1 enf_10_ll1 enf_10_at, color(gs6%20)) (scatter enf_10_b enf_10_at, msymbol(p) mc(black%60)) (line enf_10_b enf_10_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1367
+ graph export "$out_files/any_air_cen_event_10.pdf", replace
1368
+
1369
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#2.min_cen_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_15_) replace
1370
+
1371
+ twoway (rarea enf_15_ul1 enf_15_ll1 enf_15_at, color(gs6%20)) (scatter enf_15_b enf_10_at, msymbol(p) mc(black%60)) (line enf_15_b enf_15_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1372
+ graph export "$out_files/any_air_cen_event_15.pdf", replace
1373
+
1374
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#3.min_cen_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_20_) replace
1375
+
1376
+ twoway (rarea enf_20_ul1 enf_20_ll1 enf_20_at, color(gs6%20)) (scatter enf_20_b enf_20_at, msymbol(p) mc(black%60)) (line enf_20_b enf_20_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.01 0.01)) ylab(-0.01(0.005)0.01)
1377
+ graph export "$out_files/any_air_cen_event_20.pdf", replace
1378
+
1379
+
1380
+ **==============================================================================
1381
+ * Figure D5
1382
+ use "$data_files/city_enf.dta", clear
1383
+ set scheme s1mono
1384
+
1385
+ fvset base 2014 year
1386
+ fvset base 20 time
1387
+
1388
+ reghdfe log_any_air i.time##c.number i.post1##c.area i.post1##c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id) poolsize(1) compact
1389
+ coefplot, baselevels omitted vert yline(-0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) keep(*me#c.number) coeflabels() drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) le(95) mc(black) gen(pm1_) replace
1390
+
1391
+ regress number number_iv
1392
+ predict num_hat
1393
+
1394
+ reghdfe log_any_air i.time##c.num_hat i.post1##c.area i.post1##c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id) poolsize(1) compact
1395
+ coefplot, baselevels omitted vert yline(-0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) keep(*me#c.num_hat) coeflabels() drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) le(95) mc(black) gen(pm2_) replace
1396
+
1397
+ twoway (rarea pm1_ul1 pm1_ll1 pm1_at, color(gs6%20)) (line pm1_b pm1_at, lwidth(medthick) lp(dash) lc(blackblack%70)) (rarea pm2_ul1 pm2_ll1 pm2_at, color(gs6%20)) (line pm2_b pm2_at, lp(dash) lc(blackblack%40)), yline(-0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.2 0.6)) ylabel(-0.2(0.2)0.6) legend(order(2 "DiD" 4 "DiD+IV") pos(2) ring(0) rows(2))
1398
+
1399
+ graph export "$out_files/eventenf.pdf", replace
1400
+
1401
+
1402
+ **==============================================================================
1403
+ * Figure D11
1404
+ * balance
1405
+ use "$data_files/city_pm.dta", clear
1406
+ keep if year < 2015
1407
+
1408
+ replace light = log(light)
1409
+ gen log_any_air = log(any_air+1)
1410
+
1411
+ collapse (mean) pm25 light log_any_air number area pop age city_id GDP, by(city_cn)
1412
+ gen above57 = age > 57
1413
+
1414
+ label variable number "\# Monitors"
1415
+ label variable area "Size of buildup area"
1416
+ label variable pop "Urban population"
1417
+ label variable pm25 "AOD before 2015"
1418
+ label variable light "Night light before 2015"
1419
+ label variable log_any_air "log(\# Firms) before 2015"
1420
+
1421
+ fvset base 58 age
1422
+ regress number i.age if age>=50 & age<=60
1423
+ coefplot, baselevels omitted vert drop(_cons) keep(*.age) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor")coeflabels(50.age = "50" 51.age = "51" 52.age = "52" 53.age = "53" 54.age = "54" 55.age = "55" 56.age = "56" 57.age = "57" 58.age = "58" 59.age = "59" 60.age = "60") le(95)
1424
+ graph export "$out_files/number_age.pdf", replace
1425
+
1426
+ regress area i.age if age>=50 & age<=60
1427
+ coefplot, baselevels omitted vert drop(_cons) keep(*.age) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor")coeflabels(50.age = "50" 51.age = "51" 52.age = "52" 53.age = "53" 54.age = "54" 55.age = "55" 56.age = "56" 57.age = "57" 58.age = "58" 59.age = "59" 60.age = "60") le(95)
1428
+ graph export "$out_files/area_age.pdf", replace
1429
+
1430
+ regress pop i.age if age>=50 & age<=60
1431
+ coefplot, baselevels omitted vert drop(_cons) keep(*.age) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor")coeflabels(50.age = "50" 51.age = "51" 52.age = "52" 53.age = "53" 54.age = "54" 55.age = "55" 56.age = "56" 57.age = "57" 58.age = "58" 59.age = "59" 60.age = "60") le(95)
1432
+ graph export "$out_files/pop_age.pdf", replace
1433
+
1434
+ regress pm25 i.age if age>=50 & age<=60
1435
+ coefplot, baselevels omitted vert drop(_cons) keep(*.age) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor")coeflabels(50.age = "50" 51.age = "51" 52.age = "52" 53.age = "53" 54.age = "54" 55.age = "55" 56.age = "56" 57.age = "57" 58.age = "58" 59.age = "59" 60.age = "60") le(95)
1436
+ graph export "$out_files/pm_age.pdf", replace
1437
+
1438
+ regress light i.age if age>=50 & age<=60
1439
+ coefplot, baselevels omitted vert drop(_cons) keep(*.age) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor")coeflabels(50.age = "50" 51.age = "51" 52.age = "52" 53.age = "53" 54.age = "54" 55.age = "55" 56.age = "56" 57.age = "57" 58.age = "58" 59.age = "59" 60.age = "60") le(95)
1440
+ graph export "$out_files/light_age.pdf", replace
1441
+
1442
+ regress log_any_air i.age if age>=50 & age<=60
1443
+ coefplot, baselevels omitted vert drop(_cons) keep(*.age) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor")coeflabels(50.age = "50" 51.age = "51" 52.age = "52" 53.age = "53" 54.age = "54" 55.age = "55" 56.age = "56" 57.age = "57" 58.age = "58" 59.age = "59" 60.age = "60") le(95)
1444
+ graph export "$out_files/enf_age.pdf", replace
1445
+
1446
+
1447
+ **==============================================================================
1448
+ * Figure D7
1449
+ * Bandwidths
1450
+ use "$data_files/city_pm_rd.dta", clear
1451
+
1452
+ gen dist1 = area - 20 if cutoff == 1
1453
+ replace dist1 = area - 50 if cutoff == 2
1454
+
1455
+ frame create fs fs_b fs_var
1456
+ quietly{
1457
+ forvalues x = 4(2)20 {
1458
+ qui rdrobust number dist1, p(1) h(`x') kernel(uni) covs(cutoff) vce(cluster city_id)
1459
+ frame post fs (e(tau_cl)) (e(se_tau_cl))
1460
+ }
1461
+ }
1462
+
1463
+ frame fs: gen fs_ul = fs_b + 1.96*fs_var
1464
+ frame fs: gen fs_ll = fs_b - 1.96*fs_var
1465
+ frame fs: gen fs_at = 2 + 2*_n
1466
+
1467
+ frame fs: twoway (connected fs_b fs_at, sort msymbol(S) color(black)) (line fs_ul fs_at, sort lpattern(dash) lcolor(gs9)) /*
1468
+ */ (line fs_ll fs_at, sort lpattern(dash) lcolor(gs9)), ytitle(Number of monitors) yline(0, lc(cranberry)) /*
1469
+ */ xtitle(Bandwidth) xline(11.3, lcolor(blue) lpattern(dash) lwidth(thin)) /*
1470
+ */ graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ysc(r(0 2)) ylabel(0(0.5)2) xlabel(4(2)20)
1471
+ graph export "$out_files/band_fs.pdf", replace
1472
+
1473
+ gen bench = pm25 if year < 2012
1474
+ bys city_id cutoff: egen mean_bench = mean(bench)
1475
+
1476
+ frame create rd rd_b rd_var
1477
+ quietly{
1478
+ forvalues x = 4(2)20 {
1479
+ qui rdrobust pm25 dist1 if year >= 2015, fuzzy(number) covs(cutoff mean_bench year) p(1) h(`x') vce(cluster city_id) kernel(uni)
1480
+ frame post rd (e(tau_cl)) (e(se_tau_cl))
1481
+ }
1482
+ }
1483
+
1484
+ frame rd: gen rd_ul = rd_b + 1.96*rd_var
1485
+ frame rd: gen rd_ll = rd_b - 1.96*rd_var
1486
+ frame rd: gen rd_at = 2 + 2*_n
1487
+
1488
+ frame rd: twoway (connected rd_b rd_at, sort msymbol(S) color(black)) (line rd_ul rd_at, sort lpattern(dash) lcolor(gs9)) /*
1489
+ */ (line rd_ll rd_at, sort lpattern(dash) lcolor(gs9)), ytitle(Number of monitors) yline(0, lc(cranberry)) /*
1490
+ */ xtitle(Bandwidth) xline(11.3, lcolor(blue) lpattern(dash) lwidth(thin)) /*
1491
+ */ graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ysc(r(-0.075 0.05)) ylabel(-0.075(0.025)0.05) xlabel(4(2)20)
1492
+ graph export "$out_files/band_rd.pdf", replace
1493
+
1494
+
1495
+ use "$data_files/city_enf_rd.dta", clear
1496
+
1497
+ gen dist1 = area - 20 if cutoff == 1
1498
+ replace dist1 = area - 50 if cutoff == 2
1499
+
1500
+ gen bench = log_any_air if year < 2012
1501
+ bys city_id cutoff: egen mean_bench = mean(bench)
1502
+
1503
+ frame drop rd
1504
+ frame create rd rd_b rd_var
1505
+ quietly{
1506
+ forvalues x = 4(2)20 {
1507
+ qui rdrobust log_any_air dist1 if year >= 2015, fuzzy(number) covs(cutoff mean_bench year) p(1) h(`x') vce(cluster city_id) kernel(uni)
1508
+ frame post rd (e(tau_cl)) (e(se_tau_cl))
1509
+ }
1510
+ }
1511
+
1512
+ frame rd: gen rd_ul = rd_b + 1.96*rd_var
1513
+ frame rd: gen rd_ll = rd_b - 1.96*rd_var
1514
+ frame rd: gen rd_at = 2 + 2*_n
1515
+
1516
+ frame rd: twoway (connected rd_b rd_at, sort msymbol(S) color(black)) (line rd_ul rd_at, sort lpattern(dash) lcolor(gs9)) /*
1517
+ */ (line rd_ll rd_at, sort lpattern(dash) lcolor(gs9)), ytitle(Number of monitors) yline(0, lc(cranberry)) /*
1518
+ */ xtitle(Bandwidth) xline(11.3, lcolor(blue) lpattern(dash) lwidth(thin)) /*
1519
+ */ graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ysc(r(-0.2 0.6)) ylabel(-0.2(0.2)0.6) xlabel(4(2)20)
1520
+ graph export "$out_files/band_rd_enf.pdf", replace
1521
+
1522
+
1523
+ **==============================================================================
1524
+ * Figure D7
1525
+ use "$data_files/city_pm_rd.dta", clear
1526
+
1527
+ gen dist1 = area - 20 if cutoff == 1
1528
+ replace dist1 = area - 50 if cutoff == 2
1529
+
1530
+ hist dist1 if cutoff == 1 & year == 2015 & month == 1, /*
1531
+ */ start(-24) width(12) xline(0, lc(cranberry)) ysc(r(0 0.025)) /*
1532
+ */ ylabel(0(0.005)0.025) xtitle("Size of the Build-up Area") /*
1533
+ */ graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) /*
1534
+ */ plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) /*
1535
+ */ legend(nobox region(fcolor(white) margin(zero) lcolor(white)))
1536
+ graph export "$out_files/Cutoff1Score1.pdf", replace
1537
+
1538
+ hist dist1 if cutoff == 2 & year == 2015 & month == 1, /*
1539
+ */ start(-60) width(12) xline(0, lc(cranberry)) ysc(r(0 0.025)) /*
1540
+ */ ylabel(0(0.005)0.025) xtitle("Size of the Build-up Area") /*
1541
+ */ graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) /*
1542
+ */ plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) /*
1543
+ */ legend(nobox region(fcolor(white) margin(zero) lcolor(white)))
1544
+ graph export "$out_files/Cutoff2Score1.pdf", replace
1545
+
1546
+ rddensity dist1 if year==2015 & month==1 & dist1<40 & dist1>-40, all plot plot_range(-20 20) nohist graph_opt(legend(off) xtitle("Size of the Buildup Area") ytitle("Density") graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)))
1547
+ graph export "$out_files/DensityTest1.pdf", as(pdf) replace
1548
+
1549
+
1550
+ **==============================================================================
1551
+ * Figure D9
1552
+ * hist
1553
+ use "$data_files/Raw/firm_info.dta", clear
1554
+
1555
+ hist min_dist if min_dist < 50, xtitle("Distance to the closest monitor (km)") /*
1556
+ */ graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) /*
1557
+ */ plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) /*
1558
+ */ legend(nobox region(fcolor(white) margin(zero) lcolor(white)))
1559
+ graph export "$out_files/hist_min_dist.pdf", as(pdf) replace
1560
+
1561
+
1562
+
1563
+
1564
+
110/replication_package/replication/Do-file/Figure.do ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * Set Directory
2
+ clear
3
+ set more off
4
+ set scheme s1mono
5
+
6
+ cd "$path"
7
+ global data_files "$path/Data"
8
+ global out_files "$path/output"
9
+
10
+ **==============================================================================
11
+ * Figure 1
12
+ use "$data_files/firm_enf.dta", clear
13
+
14
+ fvset base 2014 year
15
+
16
+ * Binscatter plot
17
+ binscatter any_air min_dist if min_dist<50 & starty<=2010, by(post) line(none) ytitle(Any Air Pollution Related Enforcement) xtitle(Distance to the Closest Monitor(km)) legend(region(lwidth(none)) pos(12) ring(0) lab(1 pre-policy (2010-2014)) lab(2 post-policy (2015-2017))) mc(black cranberry) lc(black cranberry) ysc(r(0.001 0.013)) ylab(0.001(0.002)0.013) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white))
18
+ graph export "$out_files/any_air_gradient_50.pdf", replace
19
+
20
+ binscatter any_air year if min_dist<50 & starty<=2010, by(min_dist_10) ytitle(Any Air Pollution Related Enforcement) xtitle(Year) legend(region(lwidth(none)) pos(12) ring(0) order(2 1) lab(1 10-50km) lab(2 0-10km)) mc(black cranberry) line(none) xtick(2010(1)2017) xlabel(2010 "2010" 2011 "2011" 2012 "2012" 2013 "2013" 2014 "2014" 2015 "2015" 2016 "2016" 2017 "2017") ysc(r(0.001 0.013)) ylab(0.001(0.002)0.013) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white))
21
+ graph export "$out_files/any_air_trend.pdf", replace
22
+
23
+ use "$data_files/Raw/pm.dta", clear
24
+ drop pm25
25
+
26
+ rename pm_indirect pm3
27
+ rename pm_direct pm2
28
+
29
+ reshape long pm, i(city_id year month) j(group)
30
+
31
+ append using "$data_files/pix.dta"
32
+ replace group = 1 if group == .
33
+
34
+ egen time = group(year month)
35
+
36
+ binscatter pm year, by(group) line(none) legend(region(lwidth(none)) pos(12) ring(0) cols(3) lab(1 Monitor (≤ 10km)) lab(2 City Center (10-50km)) lab(3 Surrounding Area (> 50km))) ysc(r(0.33 0.47)) ylab(0.30(0.02)0.48) mc(cranberry black gray) m(D O S) ytitle("Aerosol Optical Depth") xtitle("Year") xtick(2010(1)2017) xlabel(2010 "2010" 2011 "2011" 2012 "2012" 2013 "2013" 2014 "2014" 2015 "2015" 2016 "2016" 2017 "2017") ysc(r(0.24 0.48)) ylab(0.24(0.04)0.48) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white))
37
+ graph export "$out_files/monitors_trend.pdf", replace
38
+
39
+ **==============================================================================
40
+ * Figure 2
41
+ use "$data_files/firm_enf.dta", clear
42
+
43
+ * set base level
44
+ fvset base 20 time
45
+ fvset base 4 min_d_d4
46
+
47
+ * Event Study Specification
48
+ reghdfe any_air i.time##i.min_d_d4 if min_dist<50 & starty<=2010, absorb(id time industry#time prov_id#time) cluster(city_id)
49
+
50
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#0.min_d_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_5_) replace
51
+
52
+ twoway (rarea enf_5_ul1 enf_5_ll1 enf_5_at, color(gs6%20)) (scatter enf_5_b enf_5_at, msymbol(p) mc(black%60)) (line enf_5_b enf_5_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.006 0.012)) ylab(-0.006(0.006)0.012)
53
+ graph export "$out_files/event_enf_min_dist5.pdf", replace
54
+
55
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#1.min_d_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_10_) replace
56
+
57
+ twoway (rarea enf_10_ul1 enf_10_ll1 enf_10_at, color(gs6%20)) (scatter enf_10_b enf_10_at, msymbol(p) mc(black%60)) (line enf_10_b enf_10_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.006 0.012)) ylab(-0.006(0.006)0.012)
58
+ graph export "$out_files/event_enf_min_dist10.pdf", replace
59
+
60
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#2.min_d_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_15_) replace
61
+
62
+ twoway (rarea enf_15_ul1 enf_15_ll1 enf_15_at, color(gs6%20)) (scatter enf_15_b enf_10_at, msymbol(p) mc(black%60)) (line enf_15_b enf_15_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.006 0.012)) ylab(-0.006(0.006)0.012)
63
+ graph export "$out_files/event_enf_min_dist15.pdf", replace
64
+
65
+ qui coefplot, baselevels omitted vert yline(0, lc(black)) xline(20.5, lc(cranberry) lp(dash)) keep(*.time#3.min_d_d4) drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) xtitle(Year) le(95) mc(black) ciopts(recast(rcap) lwidth(0.3) lpattern(dash)) gen(enf_20_) replace
66
+
67
+ twoway (rarea enf_20_ul1 enf_20_ll1 enf_20_at, color(gs6%20)) (scatter enf_20_b enf_20_at, msymbol(p) mc(black%60)) (line enf_20_b enf_20_at, lp(dash) lc(blackblack%60)), yline(0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.006 0.012)) ylab(-0.006(0.006)0.012)
68
+ graph export "$out_files/event_enf_min_dist20.pdf", replace
69
+
70
+ **==============================================================================
71
+ * Figure 3
72
+ use "$data_files/Raw/city_info.dta", clear
73
+ merge 1:1 city_id using "$data_files/share.dta"
74
+ drop if _merge == 2
75
+ drop _merge
76
+
77
+ binsreg share_rev_10 number, ci(95) graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(% of High-Pollution Activity <10km from Monitor) xtitle(# Monitors)
78
+ graph export "$out_files/revenue_share.pdf", replace
79
+
80
+ **==============================================================================
81
+ * Figure 4
82
+ use "$data_files/city_pm.dta", clear
83
+
84
+ reghdfe pm25, a(city_id) residuals(pm_res)
85
+
86
+ collapse (mean) pm_res, by(number_iv year)
87
+ twoway (line pm_res year if number==1, lc(navy)) (line pm_res year if number==2, lc(maroon)) /*
88
+ */ (line pm_res year if number==4, lc(forest_green)) (line pm_res year if number==6, lc(dkorange)), /*
89
+ */ yline(0, lc(black)) xline(2014.5, lp(dash) lc(cranberry)) graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle("Aerosol Optical Depth") xtitle("Year") xtick(2010(1)2017) xsc(r(2010 2017)) xlabel(2010 "2010" 2011 "2011" 2012 "2012" 2013 "2013" 2014 "2014" 2015 "2015" 2016 "2016" 2017 "2017") legend(off) text(-0.008 2016.8 "One" -0.05 2016.8 "Two" -0.085 2016.8 "Four" -0.097 2016.8 "Six")
90
+ graph export "$out_files/number_iv_trend.pdf", replace
91
+
92
+ use "$data_files/city_pm.dta", clear
93
+
94
+ fvset base 2014 year
95
+ fvset base 20 time
96
+ drop if year==2014 & month==12
97
+
98
+ reghdfe pm25 i.time##c.number i.post1##i.quarter##c.area i.post1##i.quarter##c.pop i.quarter##c.area i.quarter##c.pop, a(city_id year#month pred tem_meand age_year year#incentive2) cluster(city_id)
99
+ coefplot, baselevels omitted vert yline(-0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) keep(*me#c.number) coeflabels() drop() ysc(r(-0.08 0.04)) ylabel(-0.08(0.04)0.04) graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) le(95) mc(black) gen(pm1_) replace
100
+
101
+ regress number number_iv area pop
102
+ predict num_hat
103
+
104
+ reghdfe pm25 i.time##c.num_hat i.post1##i.quarter##c.area i.post1##i.quarter##c.pop i.quarter##c.area i.quarter##c.pop, a(city_id year#month pred tem_meand age_year year#incentive2) cluster(city_id)
105
+ coefplot, baselevels omitted vert yline(-0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) keep(*me#c.num_hat) coeflabels() drop() graphregion(color(white) fcolor(white)) plotregion(color(white)) ytitle(Parameter Estimate) le(95) mc(black) gen(pm2_) replace
106
+
107
+ twoway (rarea pm1_ul1 pm1_ll1 pm1_at, color(gs6%20)) (line pm1_b pm1_at, lwidth(medthick) lp(dash) lc(blackblack%70)) (rarea pm2_ul1 pm2_ll1 pm2_at, color(gs6%20)) (line pm2_b pm2_at, lp(dash) lc(blackblack%40)), yline(-0, lc(black)) xline(20.5, lp(dash) lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) ytitle("") xtitle("") xtick(1(1)32) xlabel(1 "2010" 5 "2011" 9 "2012" 13 "2013" 17 "2014" 21 "2015" 25 "2016" 29 "2017") ysc(r(-0.08 0.08)) ylabel(-0.08(0.04)0.08) legend(order(2 "DiD" 4 "DiD+IV") pos(2) ring(0) rows(2))
108
+ graph export "$out_files/eventpm.pdf", replace
109
+
110
+ **==============================================================================
111
+ * Figure 5
112
+ use "$data_files/city_pm_rd.dta", clear
113
+
114
+ gen dist1 = area - 20 if cutoff == 1
115
+ replace dist1 = area - 50 if cutoff == 2
116
+
117
+ gen bench = pm25 if year < 2012
118
+ bys city_id cutoff: egen mean_bench = mean(bench)
119
+
120
+ regress number cutoff if abs(dist1)<22
121
+ predict res_num, residuals
122
+ rdplot res_num dist1 if abs(dist1)<15 & year==2015 & month==1, p(2) h(15) nbins(5) kernel(uni) ci(95) vce(cluster city_id) graph_options(ytitle(Residualized # of Monitors) xtitle(Distance to the Closest Geographical Size Cutoff) legend(off) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(nobox region(fcolor(white) margin(zero) lcolor(white))) ysc(r(-1.5 1.5)) ylabel(-1.5(0.5)1.5) xsc(r(-15 15)) xlabel(-15(5)15))
123
+ graph export "$out_files/fs_ci.pdf", replace
124
+
125
+ regress incentive2 cutoff if abs(dist1)<22
126
+ predict res_inc2, residuals
127
+ rdplot res_inc2 dist1 if abs(dist1)<15 & year==2015 & month==1, p(2) h(15) nbins(5) kernel(uni) ci(95) vce(cluster city_id) graph_options(ytitle(Residualized Reduction Goal(%)) xtitle(Distance to the Closest Geographical Size Cutoff) legend(off) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(nobox region(fcolor(white) margin(zero) lcolor(white))) ysc(r(-10 10)) ylabel(-10(5)10) xsc(r(-15 15)) xlabel(-15(5)15))
128
+ graph export "$out_files/inc2_ci.pdf", replace
129
+
130
+ regress pm25 cutoff mean_bench if abs(dist1)<22 & year>=2015
131
+ predict res_pm, residuals
132
+ rdplot res_pm dist1 if abs(dist1)<15 & year>=2015 & year>2011, p(2) h(15) nbins(5) covs() kernel(uni) ci(95) vce(cluster city_id) graph_options(ytitle(Residualized AOD) xtitle(Distance to the Closest Geographical Size Cutoff) legend(off) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(nobox region(fcolor(white) margin(zero) lcolor(white))) ysc(r(-0.06 0.06)) ylabel(-0.06(0.03)0.06) xsc(r(-15 15)) xlabel(-15(5)15))
133
+ graph export "$out_files/rd_ci.pdf", replace
134
+
135
+ regress pm25 cutoff mean_bench if abs(dist1)<22 & year<2015 & year>2010
136
+ predict res_pm_pre, residuals
137
+ rdplot res_pm_pre dist1 if abs(dist1)<15 & year<2015 & year>2011, p(2) h(15) nbins(5) covs() kernel(uni) ci(95) vce(cluster city_id) graph_options(ytitle(Residualized AOD) xtitle(Distance to the Closest Geographical Size Cutoff) legend(off) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(nobox region(fcolor(white) margin(zero) lcolor(white))) ysc(r(-0.06 0.06)) ylabel(-0.06(0.03)0.06) xsc(r(-15 15)) xlabel(-15(5)15))
138
+ graph export "$out_files/rd_ci_pre.pdf", replace
139
+
140
+ **==============================================================================
141
+ use "$data_files/city_enf_rd.dta", clear
142
+
143
+ gen dist1 = area - 20 if cutoff == 1
144
+ replace dist1 = area - 50 if cutoff == 2
145
+
146
+ gen bench = log_any_air if year < 2012
147
+ bys city_id cutoff: egen mean_bench = mean(bench)
148
+
149
+ regress log_any_air cutoff mean_bench if abs(dist1)<22 & year>=2015
150
+ predict res_air, residuals
151
+ rdplot res_air dist1 if abs(dist1)<16 & year>=2015 & year>2011, p(2) h(15) nbins(5) covs() kernel(uni) ci(95) vce(cluster city_id) graph_options(ytitle(Residualized log(# Any Enf)) xtitle(Distance to the Closest Geographical Size Cutoff) legend(off) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(nobox region(fcolor(white) margin(zero) lcolor(white))) ysc(r(-0.5 0.5)) ylabel(-0.5(0.25)0.5) xsc(r(-15 15)) xlabel(-15(5)15))
152
+ graph export "$out_files/rd_ci_enf.pdf", replace
153
+
154
+ regress log_any_air cutoff if abs(dist1)<22 & year<2015 & year>2011
155
+ predict res_air_pre, residuals
156
+ rdplot res_air_pre dist1 if abs(dist1)<16 & year<2015 & year>2011, p(2) h(15) nbins(5) covs() kernel(uni) ci(95) vce(cluster city_id) graph_options(ytitle(Residualized log(# Any Enf)) xtitle(Distance to the Closest Geographical Size Cutoff) legend(off) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(nobox region(fcolor(white) margin(zero) lcolor(white))) ysc(r(-0.5 0.5)) ylabel(-0.5(0.25)0.5) xsc(r(-15 15)) xlabel(-15(5)15))
157
+ graph export "$out_files/rd_ci_enf_pre.pdf", replace
158
+
159
+ **==============================================================================
160
+ * Figure 6
161
+ use "$data_files/city_pm.dta", clear
162
+
163
+ fvset base 58 age
164
+ reghdfe pm25 c.post1#c.number c.post1#c.area c.post1#c.pop i.age#c.post1#c.number if age >= 50 & age <= 60, a(city_id year#month pred tem_meand incentive2#i.year) cluster(city_id)
165
+ coefplot, baselevels omitted vert keep(*age#c.post1#c.number) drop(_cons c.post1#c.number c.post1#c.area c.post1#c.pop) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor") coeflabels(50.age#c.post1#c.number = "50" 51.age#c.post1#c.number = "51" 52.age#c.post1#c.number = "52" 53.age#c.post1#c.number = "53" 54.age#c.post1#c.number = "54" 55.age#c.post1#c.number = "55" 56.age#c.post1#c.number = "56" 57.age#c.post1#c.number = "57" 58.age#c.post1#c.number = "58" 59.age#c.post1#c.number = "59" 60.age#c.post1#c.number = "60") le(95) ysc(r(-0.04 0.02)) ylab(-0.04(0.02)0.02)
166
+ graph export "$out_files/promotion_age.pdf", replace
167
+
168
+ use "$data_files/city_enf.dta", clear
169
+
170
+ fvset base 58 age
171
+ reghdfe log_any_air c.post1#c.number i.age#c.post1#c.number c.post1#c.area c.post1#c.pop if age >= 50 & age <= 60, a(city_id year#quarter incentive2#i.year) cluster(city_id)
172
+ coefplot, baselevels omitted vert keep(*age#c.post1#c.number) drop(_cons c.post1#c.number c.post1#c.area c.post1#c.pop) yline(0, lc(cranberry)) graphregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white) ilpattern(blank)) plotregion(fcolor(white) lcolor(none) ifcolor(white) ilcolor(white)) legend(off) ytitle("") xtitle("Age of Mayor") coeflabels(50.age#c.post1#c.number = "50" 51.age#c.post1#c.number = "51" 52.age#c.post1#c.number = "52" 53.age#c.post1#c.number = "53" 54.age#c.post1#c.number = "54" 55.age#c.post1#c.number = "55" 56.age#c.post1#c.number = "56" 57.age#c.post1#c.number = "57" 58.age#c.post1#c.number = "58" 59.age#c.post1#c.number = "59" 60.age#c.post1#c.number = "60") le(95) ysc(r(-0.12 0.24)) ylab(-0.12(0.12)0.24)
173
+ graph export "$out_files/promotion_age_enf.pdf", replace
174
+
175
+
176
+
177
+
110/replication_package/replication/Do-file/Install.do ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *** Install all the programs in the ado/plus-folder from internet
2
+
3
+ ssc install geodist, replace
4
+ ssc install binscatter, replace
5
+ ssc install ivreg2, replace
6
+ ssc install ranktest, replace
7
+ ssc install estout, replace
8
+ ssc install erepost, replace
9
+ ssc install coefplot, replace
10
+ ssc install tmpdir, replace
11
+ ssc install reg2hdfe, replace
12
+
13
+ cap ado uninstall rdrobust
14
+ net install rdrobust, from("https://raw.githubusercontent.com/rdpackages/rdrobust/master/stata") replace
15
+
16
+ cap ado uninstall binsreg
17
+ net install binsreg, from("https://raw.githubusercontent.com/nppackages/binsreg/master/stata") replace
18
+
19
+ cap ado uninstall ftools
20
+ net install ftools, from("https://raw.githubusercontent.com/sergiocorreia/ftools/master/src/") replace
21
+
22
+ cap ado uninstall reghdfe
23
+ net install reghdfe, from("https://raw.githubusercontent.com/sergiocorreia/reghdfe/master/src/") replace
24
+
25
+ cap ado uninstall ivreghdfe
26
+ net install ivreghdfe, from("https://raw.githubusercontent.com/sergiocorreia/ivreghdfe/master/src/") replace
27
+
28
+ cap ado uninstall lpdensity
29
+ net install lpdensity, from("https://raw.githubusercontent.com/nppackages/lpdensity/master/stata") replace
30
+
31
+ cap ado uninstall rddensity
32
+ net install rddensity, from("https://raw.githubusercontent.com/rdpackages/rddensity/master/stata") replace */
33
+
34
+
35
+ ***The End
36
+
37
+
38
+
39
+
110/replication_package/replication/Do-file/MakeData.do ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * Set Directory
2
+ clear
3
+ set more off
4
+ set scheme s1mono
5
+
6
+ cd "$path"
7
+ global data_files "$path/Data"
8
+ global out_files "$path/output"
9
+
10
+ **==============================================================================
11
+ * Weather data
12
+ use "$data_files/Raw/weather_daily.dta", clear
13
+
14
+ collapse (sum) pre (mean) tem_mean, by(city_id year month)
15
+ save "$data_files/weather_monthly.dta", replace
16
+
17
+ use "$data_files/Raw/weather_daily.dta", clear
18
+ gen quarter = int((month-1)/3)+1
19
+
20
+ collapse (sum) pre (mean) tem_mean, by(city_id year quarter)
21
+ save "$data_files/weather_quarterly.dta", replace
22
+
23
+ use "$data_files/Raw/weather_daily.dta", clear
24
+ gen quarter = int((month-1)/3)+1
25
+
26
+ bys city_id year quarter: egen wd = mode(wdmax), max
27
+ keep city_id year quarter wd
28
+ duplicates drop
29
+ save "$data_files/wind_quarterly.dta", replace
30
+
31
+ **==============================================================================
32
+ * Firm-level: enforcement data
33
+ use "$data_files/Raw/firm_info.dta", clear
34
+
35
+ merge 1:m id using "$data_files/Raw/enf_info.dta"
36
+ keep if _merge == 3
37
+ drop _merge
38
+
39
+ merge m:1 city_id year quarter using "$data_files/weather_quarterly.dta"
40
+ keep if _merge == 3
41
+ drop _merge
42
+
43
+ merge m:1 city_id year quarter using "$data_files/wind_quarterly.dta"
44
+ keep if _merge == 3
45
+ drop _merge
46
+
47
+ capture drop ibear
48
+ program ibear
49
+
50
+ args lat1 lon1 lat2 lon2 newvar
51
+
52
+ tempname d2r r2d
53
+ scalar `d2r' = _pi / 180
54
+ scalar `r2d' = 180 / _pi
55
+
56
+ gen `newvar' = atan2(sin((`lon2'-`lon1') * `d2r') * cos(`lat2' * `d2r') , ///
57
+ cos(`lat1' * `d2r') * sin(`lat2' * `d2r') - ///
58
+ sin(`lat1' * `d2r') * cos(`lat2' * `d2r') * ///
59
+ cos((`lon2'-`lon1') * `d2r'))
60
+
61
+ // normalize atan2 results (-pi to pi) to range from 0 to 360 degrees
62
+ replace `newvar' = mod((`newvar' * `r2d') + 360,3 60)
63
+
64
+ end
65
+
66
+ ibear monitor_lat monitor_lon lat lon angle
67
+ replace wd = 22.5*(wd-1)
68
+
69
+ gen upwd = 1 if angle - wd < 45 & angle - wd > -45
70
+ replace upwd = 1 if (angle - wd < 45 | angle - 360 - wd > -45) & wd <= 45
71
+ replace upwd = 1 if (angle + 360 - wd < 45 | angle - wd > -45) & wd >= 315
72
+ replace upwd = 0 if upwd == .
73
+
74
+ egen time = group(year quarter)
75
+ gen min_dist_10 = min_dist < 10
76
+ gen post1 = year >= 2015
77
+
78
+ gen air_1 = air==1
79
+ gen air_2 = air>=2
80
+
81
+ gen leni = (any_air_shutdown + any_air_fine + any_air_renovate == 1)
82
+ gen stri = (any_air_shutdown + any_air_fine + any_air_renovate == 3)
83
+
84
+ gen min_d_d4 = int(min_dist/5)
85
+ replace min_d_d4 = 4 if min_d_d4 > 4
86
+
87
+ bysort city_id: egen med_pre=median(pre)
88
+ gen high_pre=0 if pre!=.
89
+ replace high_pre=1 if pre!=. & pre>med_pre
90
+
91
+ save "$data_files/firm_enf.dta", replace
92
+
93
+ **==============================================================================
94
+ use "$data_files/firm_enf.dta", clear
95
+
96
+ gen any_air_10 = any_air & min_dist < 10
97
+ gen any_air_20 = any_air & min_dist < 50 & min_dist > 10
98
+ gen any_air_50 = any_air & min_dist > 50
99
+
100
+ collapse (sum) any_air any_air_*, by(city_id year quarter)
101
+ save "$data_files/enf.dta", replace
102
+
103
+ **==============================================================================
104
+ * Mayor data
105
+ use "$data_files/Raw/mayor.dta", clear
106
+ format %td start_date
107
+ format %td end_date
108
+ format %td birthdate
109
+
110
+ bysort city_cn city_id (start_date end_date): gen next_start=start_date[_n+1]
111
+ replace next_start=end_date if next_start==.
112
+ format %td next_start
113
+
114
+ foreach v of varlist start_date next_start end_date {
115
+ gen `v'_m = mofd(`v')
116
+ format %tm `v'_m
117
+ }
118
+
119
+ bysort city_cn city_id (start_date next_start_m): replace next_start_m=next_start_m-1 if _n!=_N
120
+ expand next_start_m-start_date_m + 1
121
+
122
+ by city_cn city_id name start_date (next_start_m), sort: gen month_date = start_date_m + _n - 1
123
+ format month_date %tm
124
+ gen month=month(dofm(month_date))
125
+ gen year=year(dofm(month_date))
126
+
127
+ sort city_cn city_id month_date name
128
+
129
+ destring city_id, replace
130
+ drop if city_id==.
131
+ save "$data_files/mayor_panel.dta", replace
132
+
133
+ keep if year==2015
134
+ format %td birthdate
135
+ gen birth_year=year(birthdate)
136
+ gen birth_month=month(birthdate)
137
+ gen age_2017=2018-birth_year
138
+ bysort city_id: egen age = mode(age_2017), maxmode
139
+ bysort city_id: egen age_month = mode(birth_month), maxmode
140
+
141
+ keep city_id city_cn age age_month
142
+ duplicates drop
143
+
144
+ replace age = age+1 if age_month==1 & age==57
145
+ drop age_month
146
+
147
+ save "$data_files/age_2017.dta", replace
148
+
149
+ use "$data_files/mayor_panel.dta", clear
150
+ format %td birthdate
151
+ gen birth_year=year(birthdate)
152
+ gen birth_month=month(birthdate)
153
+
154
+ gen age = year-birth_year
155
+ bys city_id year: egen age_year = mode(age)
156
+
157
+ keep if year >= 2010 & year <= 2017
158
+ keep city_id year age_year
159
+ duplicates drop
160
+
161
+ bys city_id (year): replace age_year = age_year[_n-1]+1 if age_year == .
162
+ bys city_id (year): replace age_year = age_year[_n+1]-1 if age_year == .
163
+ bys city_id (year): replace age_year = age_year[_n-1]+1 if age_year == .
164
+ bys city_id (year): replace age_year = age_year[_n+1]-1 if age_year == .
165
+
166
+ save "$data_files/age_year.dta", replace
167
+
168
+ **==============================================================================
169
+ * Monitor data
170
+ use "$data_files/raw/pm_pix.dta", clear
171
+
172
+ keep city_id p_id p_lon p_lat
173
+ duplicates drop
174
+
175
+ rename city_id city_id2
176
+ joinby city_id2 using "$data_files/Raw/monitor_city_long.dta"
177
+
178
+ geodist p_lat p_lon monitor_lat monitor_lon, gen(dist)
179
+ keep if dist < 20
180
+
181
+ expand 8
182
+ bys city_id monitor_id p_id: gen year = 2009 + _n
183
+ expand 12
184
+ bys city_id monitor_id p_id year: gen month = _n
185
+
186
+ merge m:1 p_id year month using "$data_files/raw/pm_pix.dta"
187
+ keep if _merge == 3
188
+ drop _merge
189
+
190
+ drop if pm25 == .
191
+ bys monitor_id year month (dist): keep if _n == 1
192
+
193
+ keep monitor_id city_id year month pm25 compare
194
+ save "$data_files/monitor_pix.dta", replace
195
+
196
+ keep if compare == 0
197
+ collapse (mean) pm25, by(city_id year month)
198
+ rename pm25 pm
199
+
200
+ save "$data_files/pix.dta", replace
201
+
202
+ **==============================================================================
203
+ * City-level: AOD data
204
+ use "$data_files/Raw/city_info.dta", clear
205
+
206
+ merge 1:m city_id using "$data_files/raw/pm.dta"
207
+ keep if _merge == 3
208
+ drop _merge
209
+
210
+ merge 1:1 city_id year month using "$data_files/weather_monthly.dta"
211
+ keep if _merge == 3
212
+ drop _merge
213
+
214
+ merge m:1 city_id using "$data_files/age_2017.dta"
215
+ keep if _merge == 3
216
+ drop _merge
217
+
218
+ merge m:1 city_id year using "$data_files/age_year.dta"
219
+ keep if _merge == 3
220
+ drop _merge
221
+
222
+ merge 1:1 city_id year month using "$data_files/Raw/lights.dta"
223
+ keep if _merge == 3
224
+ drop _merge
225
+
226
+ gen pred = int(pre/20)
227
+ gen tem_meand = int(tem_mean)
228
+
229
+ sort city_id year month
230
+ gen quarter = int((month-1)/3)+1
231
+ egen time = group(year quarter)
232
+
233
+ merge m:1 city_id year quarter using "$data_files/enf.dta", keepusing(any_air)
234
+ replace any_air = 0 if _merge == 1
235
+ drop _merge
236
+
237
+ gen post1 = year >= 2015
238
+
239
+ merge 1:1 city_id year month using "$data_files/pix.dta"
240
+ drop _merge
241
+
242
+ save "$data_files/city_pm.dta", replace
243
+
244
+ expand 2, gen(cutoff)
245
+ replace cutoff = cutoff + 1
246
+ save "$data_files/city_pm_rd.dta", replace
247
+
248
+ **==============================================================================
249
+ * City-level: Enforcement data
250
+ use "$data_files/Raw/city_info.dta", clear
251
+ expand 8
252
+ bys city_id: gen year = _n + 2009
253
+ expand 4
254
+ bys city_id year: gen quarter = _n
255
+
256
+ merge 1:1 city_id year quarter using "$data_files/weather_quarterly.dta"
257
+ drop _merge
258
+
259
+ merge 1:1 city_id year quarter using "$data_files/enf.dta"
260
+ drop _merge
261
+
262
+ merge m:1 city_id using "$data_files/age_2017.dta"
263
+ keep if _merge == 3
264
+ drop _merge
265
+
266
+ merge m:1 city_id year using "$data_files/age_year.dta"
267
+ keep if _merge == 3
268
+ drop _merge
269
+
270
+ gen pred = int(pre/20)
271
+ gen tem_meand = int(tem_mean)
272
+
273
+ sort city_id year quarter
274
+ egen time = group(year quarter)
275
+
276
+ replace any_air = 0 if any_air == .
277
+ gen log_any_air = log(any_air+1)
278
+
279
+ replace any_air_10 = 0 if any_air_10 == .
280
+ gen log_any_air_10 = log(any_air_10+1)
281
+ replace any_air_20 = 0 if any_air_20 == .
282
+ gen log_any_air_20 = log(any_air_20+1)
283
+
284
+ replace any_air_50 = 0 if any_air_50 == .
285
+ gen log_any_air_50 = log(any_air_50+1)
286
+
287
+ gen post1 = year >= 2015
288
+
289
+ merge 1:1 city_id year quarter using "$data_files/Raw/non-asif.dta"
290
+ drop _merge
291
+
292
+ save "$data_files/city_enf.dta", replace
293
+
294
+ expand 2, gen(cutoff)
295
+ replace cutoff = cutoff + 1
296
+ save "$data_files/city_enf_rd.dta", replace
297
+
298
+ **==============================================================================
299
+ use "$data_files/Raw/daily_monitor_api.dta", clear
300
+
301
+ collapse (mean) pm25api pm10api AQI, by(city_id monitor_id year month)
302
+ save "$data_files/monthly_api.dta", replace
303
+
304
+ **==============================================================================
305
+ use "$data_files/Raw/monitor_info.dta", clear
306
+
307
+ merge 1:m monitor_id using "$data_files/monitor_pix"
308
+ keep if _merge == 3
309
+ drop _merge
310
+
311
+ keep if year>=2015 & year<=2017
312
+
313
+ merge 1:1 monitor_id year month using "$data_files/monthly_api.dta"
314
+ keep if _merge == 3
315
+ drop _merge
316
+
317
+ merge m:1 city_id year month using "$data_files/weather_monthly.dta"
318
+ keep if _merge == 3
319
+ drop _merge
320
+
321
+ merge m:1 city_id year using "$data_files/age_year.dta"
322
+ keep if _merge == 3
323
+ drop _merge
324
+
325
+ save "$data_files/monitor_api.dta", replace
326
+
327
+ **==============================================================================
328
+ use "$data_files/Raw/firm_info.dta", clear
329
+
330
+ keep if key == 1
331
+ gen revenue_5 = revenue if min_dist < 5
332
+ gen revenue_10 = revenue if min_dist < 10
333
+
334
+ gen employment_5 = employment if min_dist < 5
335
+ gen employment_10 = employment if min_dist < 10
336
+
337
+ collapse (sum) revenue* employment*, by(city_id)
338
+
339
+ gen share_rev_10 = revenue_10/revenue
340
+ gen share_rev_5 = revenue_5/revenue
341
+
342
+ gen share_emp_10 = employment_10/employment
343
+ gen share_emp_5 = employment_5/employment
344
+
345
+ keep share* city_id
346
+ save "$data_files/share.dta", replace
347
+
348
+
349
+
350
+
351
+
110/replication_package/replication/Do-file/Master.do ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *** Master file for set path. Then run master file to produce all output.
2
+
3
+ global path "C:/Users/s14756/Desktop/replication"
4
+ cd "$path/Do-file"
5
+
6
+ sysdir set PLUS "$path/ado/plus"
7
+ sysdir set PERSONAL "$path/ado/personal"
8
+
9
+ do "$path/Do-file/MakeData.do"
10
+ do "$path/Do-file/Figure.do"
11
+ do "$path/Do-file/Table.do"
12
+ do "$path/Do-file/Appendix.do"
13
+
14
+
15
+ ***The End
16
+
17
+
18
+
19
+
110/replication_package/replication/Do-file/Table.do ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ * Set Directory
2
+ clear
3
+ set more off
4
+ set scheme s1mono
5
+
6
+ cd "$path"
7
+ global data_files "$path/Data"
8
+ global out_files "$path/output"
9
+
10
+ **==============================================================================
11
+ * Table 1-2
12
+ // Conley
13
+ use "$data_files/firm_enf.dta", clear
14
+ keep if min_dist<50 & starty<=2010
15
+ drop if revenue == .
16
+ drop if key == .
17
+
18
+ label var min_dist_10 "Mon\$\_{<10km}\$"
19
+ label var any_air "Any Enforcement (0/1)"
20
+ label var post "Post"
21
+ label var key "High Pollution"
22
+
23
+ gen min_dist_10_post1 = c.min_dist_10#c.post1
24
+ egen ind_time = group(industry prov_id time)
25
+
26
+ reg2hdfespatial any_air min_dist_10_post1, lat(lat) lon(lon) timevar(time) panelvar(id) altfetime(ind_time) distcutoff(100) lagcutoff(20)
27
+ scalar Conley1 = _se[min_dist_10_post1]
28
+
29
+ reg2hdfespatial any_air_shutdown min_dist_10_post1, lat(lat) lon(lon) timevar(time) panelvar(id) altfetime(ind_time) distcutoff(100) lagcutoff(20)
30
+ scalar Conley2 = _se[min_dist_10_post1]
31
+
32
+ reg2hdfespatial any_air_renovate min_dist_10_post1, lat(lat) lon(lon) timevar(time) panelvar(id) altfetime(ind_time) distcutoff(100) lagcutoff(20)
33
+ scalar Conley3 = _se[min_dist_10_post1]
34
+
35
+ reg2hdfespatial any_air_fine min_dist_10_post1, lat(lat) lon(lon) timevar(time) panelvar(id) altfetime(ind_time) distcutoff(100) lagcutoff(20)
36
+ scalar Conley4 = _se[min_dist_10_post1]
37
+
38
+ reg2hdfespatial any_air_warning min_dist_10_post1, lat(lat) lon(lon) timevar(time) panelvar(id) altfetime(ind_time) distcutoff(100) lagcutoff(20)
39
+ scalar Conley5 = _se[min_dist_10_post1]
40
+
41
+ use "$data_files/firm_enf.dta", clear
42
+ drop if revenue == .
43
+ drop if key == .
44
+
45
+ label var min_dist_10 "Mon\$\_{<10km}\$"
46
+ label var any_air "Any Enforcement (0/1)"
47
+ label var post "Post"
48
+ label var key "High Pollution"
49
+
50
+ eststo clear
51
+ reghdfe any_air c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
52
+ eststo A
53
+ estadd ysumm, mean
54
+ estadd scalar EN = e(N_full)
55
+ estadd local Conley = "[`: di %9.5f Conley1']"
56
+ reghdfe any_air_shutdown c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
57
+ eststo B
58
+ estadd ysumm, mean
59
+ estadd scalar EN = e(N_full)
60
+ estadd local Conley = "[`: di %9.5f Conley2']"
61
+ reghdfe any_air_renovate c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
62
+ eststo C
63
+ estadd ysumm, mean
64
+ estadd scalar EN = e(N_full)
65
+ estadd local Conley = "[`: di %9.5f Conley3']"
66
+ reghdfe any_air_fine c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
67
+ eststo D
68
+ estadd ysumm, mean
69
+ estadd scalar EN = e(N_full)
70
+ estadd local Conley = "[`:di %9.5f Conley4']"
71
+ reghdfe any_air_warning c.min_dist_10#c.post1 if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
72
+ eststo E
73
+ estadd ysumm, mean
74
+ estadd scalar EN = e(N_full)
75
+ estadd local Conley = "[`:di %9.5f Conley5']"
76
+ esttab A B C D E using "$out_files/Table1a.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(c.min_dist_10*) stats(ymean EN Conley, labels("Mean Outcome" "Observations" "Conley SE")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
77
+
78
+ * Table 1b
79
+ use "$data_files/firm_enf.dta", clear
80
+ drop if revenue == .
81
+ drop if key == .
82
+
83
+ label var min_dist_10 "Mon\$\_{<10km}\$"
84
+ label var any_air "Any Enforcement (0/1)"
85
+ label var post "Post"
86
+ label var key "High Pollution"
87
+
88
+ eststo clear
89
+ reghdfe air c.min_dist_10#c.post1##c.key if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
90
+ eststo A
91
+ estadd ysumm, mean
92
+ estadd scalar EN = e(N_full)
93
+ reghdfe air_1 c.min_dist_10#c.post1##c.key if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
94
+ eststo B
95
+ estadd ysumm, mean
96
+ estadd scalar EN = e(N_full)
97
+ reghdfe air_2 c.min_dist_10#c.post1##c.key if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
98
+ eststo C
99
+ estadd ysumm, mean
100
+ estadd scalar EN = e(N_full)
101
+ reghdfe leni c.min_dist_10#c.post1##c.key if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
102
+ eststo D
103
+ estadd ysumm, mean
104
+ estadd scalar EN = e(N_full)
105
+ reghdfe stri c.min_dist_10#c.post1##c.key if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
106
+ eststo E
107
+ estadd ysumm, mean
108
+ estadd scalar EN = e(N_full)
109
+ esttab A B C D E using "$out_files/Table1b.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(c.min_dist_10*) stats(ymean EN, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
110
+
111
+ * Table 2
112
+ gen Shock = high_pre
113
+ eststo clear
114
+ reghdfe any_air c.min_dist_10#c.post1##c.Shock tem_mean if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
115
+ eststo A
116
+ estadd ysumm, mean
117
+ estadd scalar EN = e(N_full)
118
+ reghdfe any_air c.min_dist_10##c.post1##c.Shock tem_mean if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
119
+ eststo B
120
+ estadd ysumm, mean
121
+ estadd scalar EN = e(N_full)
122
+ replace Shock = upwd
123
+ reghdfe any_air c.min_dist_10#c.post1##c.Shock tem_mean if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
124
+ eststo C
125
+ estadd ysumm, mean
126
+ estadd scalar EN = e(N_full)
127
+ reghdfe any_air c.min_dist_10##c.post1##c.Shock tem_mean if min_dist<50 & starty<=2010, absorb(time id industry#time prov_id#time) cluster(city_id)
128
+ eststo D
129
+ estadd ysumm, mean
130
+ estadd scalar EN = e(N_full)
131
+ esttab A B C D using "$out_files/Table2.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep() drop(_cons tem_mean post1 min_dist_10) order(Shock c.min_dist_10#c.post1 c.min_dist_10#c.Shock c.min_dist_10#c.post1#c.Shock) stats(ymean EN, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
132
+
133
+ **==============================================================================
134
+ * Table 3
135
+ use "$data_files/city_pm.dta", clear
136
+ label variable post1 "Post"
137
+ label variable number "\# Mon"
138
+ label variable number_iv "Min \# Mon"
139
+
140
+ gen RD_Estimate = c.post1#c.number
141
+
142
+ eststo clear
143
+ reghdfe pm25 RD_Estimate c.post#c.area c.post#c.pop, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
144
+ estadd scalar EN = e(N_full)
145
+ eststo A
146
+ ivreghdfe pm25 c.post#c.area c.post#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
147
+ estadd scalar EN = e(N_full)
148
+ eststo B
149
+
150
+ use "$data_files/city_pm_rd.dta", clear
151
+
152
+ gen dist1 = area - 20 if cutoff == 1
153
+ replace dist1 = area - 50 if cutoff == 2
154
+
155
+ gen bench = pm25 if year < 2012
156
+ bys city_id cutoff: egen mean_bench = mean(bench)
157
+
158
+ gen above = dist1 > 0
159
+ gen RD_Estimate = c.post1#c.above
160
+
161
+ rdrobust pm25 dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year month) kernel(uni) vce(cluster city_id)
162
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
163
+ estadd scalar band = e(h_l)
164
+ eststo C
165
+ reghdfe pm25 RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
166
+ estadd scalar EN = e(N)
167
+ estadd scalar band = 11.3
168
+ eststo D
169
+ esttab A B C D using "$out_files/Table3a.tex", keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN, labels( "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) tex
170
+
171
+ use "$data_files/city_enf.dta", clear
172
+
173
+ label variable post1 "Post"
174
+ label variable number "\# Mon"
175
+ label variable number_iv "Min \# Mon"
176
+
177
+ gen RD_Estimate = c.post1#c.number
178
+
179
+ eststo clear
180
+ reghdfe log_any_air RD_Estimate c.post#c.area c.post#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
181
+ estadd scalar EN = e(N_full)
182
+ eststo A
183
+ ivreghdfe log_any_air c.post#c.area c.post#c.pop (RD_Estimate=c.post1#c.number_iv), a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
184
+ estadd scalar EN = e(N_full)
185
+ eststo B
186
+
187
+ use "$data_files/city_enf_rd.dta", clear
188
+
189
+ gen dist1 = area - 20 if cutoff == 1
190
+ replace dist1 = area - 50 if cutoff == 2
191
+
192
+ gen bench = log_any_air if year < 2012
193
+ bys city_id cutoff: egen mean_bench = mean(bench)
194
+
195
+ gen above = dist1 > 0
196
+ gen RD_Estimate = c.post1#c.above
197
+
198
+ rdrobust log_any_air dist1 if year>=2015, fuzzy(number) p(1) h(11.3) covs(cutoff mean_bench year quarter) kernel(uni) vce(cluster city_id)
199
+ estadd scalar EN = e(N_h_l) + e(N_h_r)
200
+ estadd scalar band = e(h_l)
201
+ eststo C
202
+ reghdfe log_any_air RD_Estimate post1 above dist1 c.post1#c.dist1 c.above#c.dist1 c.post1#c.above#c.dist1 cutoff if abs(dist1) < 11.3, a(time) cl(city_id)
203
+ estadd scalar EN = e(N)
204
+ estadd scalar band = 11.3
205
+ eststo D
206
+ esttab A B C D using "$out_files/Table3b.tex", tex keep(RD_Estimate) transform(@/1.21 1/1.21, pattern(0 0 0 1)) replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers mlabels(none) coeflabels(RD_Estimate "\# Monitors") stats(EN, labels("Observations")) starlevels(* 0.10 ** 0.05 *** 0.01)
207
+
208
+ replace RD_Estimate = number_iv
209
+
210
+ eststo clear
211
+ regress number number_iv if year>=2015, vce(cluster city_id)
212
+ eststo A
213
+ regress number RD_Estimate pop area if year>=2015, vce(cluster city_id)
214
+ eststo B
215
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) covs(cutoff) kernel(uni) vce(cluster city_id)
216
+ eststo C
217
+ estadd local kern = "Uniform"
218
+ estadd scalar band = 11.3
219
+ rdrobust number dist1 if year>=2015, p(1) h(11.3) covs(cutoff) kernel(uni) vce(cluster city_id)
220
+ eststo D
221
+ estadd local kern = "Uniform"
222
+ estadd scalar band = 11.3
223
+ esttab A B C D using "$out_files/Table3c.tex", tex replace b(a2) se(a2) label noconstant nolines nogaps compress fragment nonumbers noobs mlabels(none) keep(RD_Estimate) coeflabels(RD_Estimate "Estimate") stats(kern band, labels("Kernel" "Bandwidth")) starlevels(* 0.10 ** 0.05 *** 0.01)
224
+
225
+
226
+ **==============================================================================
227
+ * Table 4
228
+ use "$data_files/monitor_api.dta", clear
229
+
230
+ gen log_pm25api = log(pm25api)
231
+ gen log_pm10api = log(pm10api)
232
+
233
+ gen reassign = (year == 2017)
234
+ replace reassign = 1 if year == 2016 & month >= 11
235
+
236
+ rename pm25 AOD
237
+ label variable AOD "AOD"
238
+ label variable reassign "Reassigned"
239
+
240
+ eststo clear
241
+ reghdfe log_pm25api AOD pre tem_mean, a(monitor_id year#month) cl(city_id)
242
+ eststo A
243
+ estadd ysumm, mean
244
+ reghdfe log_pm25api AOD pre tem_mean if ~compare, a(monitor_id year#month) cl(city_id)
245
+ eststo B
246
+ estadd ysumm, mean
247
+ reghdfe log_pm25api AOD c.AOD#c.reassign pre tem_mean if ~compare, a(monitor_id year#month) cl(city_id)
248
+ eststo C
249
+ estadd ysumm, mean
250
+ reghdfe log_pm25api AOD pre tem_mean if compare, a(monitor_id year#month) cl(city_id)
251
+ eststo D
252
+ estadd ysumm, mean
253
+ reghdfe log_pm25api AOD c.AOD#c.reassign pre tem_mean if compare, a(monitor_id year#month) cl(city_id)
254
+ eststo E
255
+ estadd ysumm, mean
256
+
257
+ use "$data_files/city_pm.dta", clear
258
+
259
+ label variable post1 "Post"
260
+ label variable number "\# Mon"
261
+
262
+ gen reassign = (year == 2017)
263
+ replace reassign = 1 if year == 2016 & month >= 10
264
+ label variable reassign "Reassigned"
265
+
266
+ reghdfe pm25 c.post1#c.number c.post1#c.number#c.reassign c.post1#c.area c.post1#c.pop, a(city_id year#month pred tem_meand age_year incentive2#time) cluster(city_id)
267
+ eststo F
268
+ estadd ysumm, mean
269
+
270
+ use "$data_files/city_enf.dta", clear
271
+
272
+ label variable post1 "Post"
273
+ label variable number "\# Mon"
274
+
275
+ gen reassign = (year == 2017)
276
+ replace reassign = 1 if year == 2016 & quarter == 4
277
+ label variable reassign "Reassigned"
278
+
279
+ reghdfe log_any_air c.post1#c.number c.post1#c.number#c.reassign c.post1#c.area c.post1#c.pop, a(city_id year#quarter pred tem_meand age_year incentive2#time) cluster(city_id)
280
+ eststo G
281
+ estadd ysumm, mean
282
+ esttab A B C D E F G using "$out_files/Table4.tex", replace b(a2) noconstant se(a2) nolines nogaps compress fragment nonumbers label mlabels(none) collabels() keep(AOD c.AOD#c.reassign c.post1#c.number c.post1#c.number#c.reassign) drop() coeflabels(c.AOD#c.reassign "AOD $\times$ Reassigned" c.post1#c.number "\# Monitors" c.post1#c.number#c.reassign "\# Monitors $\times$ Reassigned") stats(ymean N, labels("Mean Outcome" "Observations")) starlevels(* 0.10 ** 0.05 *** 0.01) substitute(\_ _) tex
283
+
284
+
110/replication_package/replication/Do-file/classify.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import csv
3
+ import os
4
+ import re
5
+ from bs4 import BeautifulSoup
6
+
7
+ def FindKey(RecordText, KeyWords):
8
+
9
+ if any(word in RecordText for word in KeyWords):
10
+ output = 1
11
+ else:
12
+ output = 0
13
+
14
+ return output
15
+
16
+
17
+ KeyWords1 = ['气','烟','尘','二氧化硫','颗粒','脱硝','脱硫','炉','焚烧','NO','PM']
18
+ KeyWords2 = ['污水','水污染','沉淀','沟','渠','COD']
19
+ KeyWords3 = ['固体']
20
+ KeyWords4 = ['未批先建','批建不符','未验先投','清理明细表','开工','环评','手续','三同时','未经验收']
21
+ KeyWords5 = ['罚款','经济处罚','万元']
22
+ KeyWords6 = ['停']
23
+ KeyWords7 = ['改','维修']
24
+
25
+ htfile = "output.txt"
26
+ fo = open(htfile, "w", encoding='utf_8_sig')
27
+
28
+
29
+ with open('records.csv', 'r') as f:
30
+ reader = csv.reader(f)
31
+ records_list = list(reader)
32
+
33
+
34
+ for record in records_list:
35
+ dir_path = '/Volumes/forMac/list/'+str(record[0])
36
+ address = dir_path+'/'+str(record[1])
37
+ print(address)
38
+
39
+ fo.write(str(record[1]))
40
+ soup = BeautifulSoup(open(address).read(), "html.parser")
41
+
42
+ output1=0
43
+ output2=0
44
+ output3=0
45
+ output4=0
46
+ output5=0
47
+ output6=0
48
+ output7=0
49
+
50
+ tables = soup.find_all('table')
51
+ cells = soup.find_all(style="color:#eeeeee;background-color:#3399FF")
52
+
53
+ if len(cells)==0:
54
+ output1=0
55
+ output2=0
56
+ output3=0
57
+ else:
58
+ if len(tables)==0:
59
+ text = soup.get_text()
60
+ else:
61
+ try:
62
+ block = cells[-1].find_parents('tr')[-1]
63
+ row = block.find_all('td')
64
+ if len(row)<4:
65
+ text = soup.get_text()
66
+ else:
67
+ text = block.get_text()
68
+ except:
69
+ text = soup.get_text()
70
+
71
+ output1 = FindKey(text, KeyWords1)
72
+ output2 = FindKey(text, KeyWords2)
73
+ output3 = FindKey(text, KeyWords3)
74
+ output4 = FindKey(text, KeyWords4)
75
+ output5 = FindKey(text, KeyWords5)
76
+ output6 = FindKey(text, KeyWords6)
77
+ output7 = FindKey(text, KeyWords7)
78
+
79
+ total=output1+output2+output3+output4
80
+
81
+ if total==0:
82
+ text = soup.get_text()
83
+ output4 = FindKey(text, KeyWords4)
84
+
85
+ fo.write(",")
86
+ fo.write(str(output1))
87
+ fo.write(",")
88
+ fo.write(str(output2))
89
+ fo.write(",")
90
+ fo.write(str(output3))
91
+ fo.write(",")
92
+ fo.write(str(output4))
93
+ fo.write(",")
94
+ fo.write(str(output5))
95
+ fo.write(",")
96
+ fo.write(str(output6))
97
+ fo.write(",")
98
+ fo.write(str(output7))
99
+ fo.write("\n")
100
+
101
+ fo.close()
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
110/replication_package/replication/ado/personal/ols_spatial_HAC.ado ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ program ols_spatial_HAC, eclass byable(recall)
2
+ version 11
3
+ syntax varlist(ts fv min=2) [if] [in], ///
4
+ lat(varname numeric) lon(varname numeric) ///
5
+ Timevar(varname numeric) Panelvar(varname numeric) [LAGcutoff(integer 0) DISTcutoff(real 1) ///
6
+ DISPlay star bartlett dropvar]
7
+
8
+ /*--------PARSING COMMANDS AND SETUP-------*/
9
+
10
+ capture drop touse
11
+ marksample touse // indicator for inclusion in the sample
12
+ gen touse = `touse'
13
+
14
+ //parsing variables
15
+ loc Y = word("`varlist'",1)
16
+
17
+ loc listing "`varlist'"
18
+
19
+ loc X ""
20
+ scalar k = 0
21
+
22
+ //make sure that Y is not included in the other_var list
23
+ foreach i of loc listing {
24
+ if "`i'" ~= "`Y'"{
25
+ loc X "`X' `i'"
26
+ scalar k = k + 1 // # indep variables
27
+
28
+ }
29
+ }
30
+
31
+
32
+ //Kyle Meng's code to drop omitted variables that Stata would drop due to collinearity
33
+
34
+ if "`dropvar'" == "dropvar"{
35
+
36
+ quietly reg `Y' `X' if `touse', nocons
37
+
38
+ mat omittedMat=e(b)
39
+ local newVarList=""
40
+ local i=1
41
+ scalar k = 0 //replace the old k if this option is selected
42
+
43
+ foreach var of varlist `X'{
44
+ if omittedMat[1,`i']!=0{
45
+ loc newVarList "`newVarList' `var'"
46
+ scalar k = k + 1
47
+ }
48
+ local i=`i'+1
49
+ }
50
+
51
+ loc X "`newVarList'"
52
+ }
53
+
54
+ //generating a function of the included obs
55
+ quietly count if `touse'
56
+ scalar n = r(N) // # obs
57
+ scalar n_obs = r(N)
58
+
59
+ /*--------FIRST DO OLS, STORE RESULTS-------*/
60
+
61
+
62
+ quietly: reg `Y' `X' if `touse', nocons
63
+ estimates store OLS
64
+
65
+ //est tab OLS, stats(N r2)
66
+
67
+ /*--------SECOND, IMPORT ALL VALUES INTO MATA-------*/
68
+
69
+ mata{
70
+
71
+ Y_var = st_local("Y") //importing variable assignments to mata
72
+ X_var = st_local("X")
73
+ lat_var = st_local("lat")
74
+ lon_var = st_local("lon")
75
+ time_var = st_local("timevar")
76
+ panel_var = st_local("panelvar")
77
+
78
+ //NOTE: values are all imported as "views" instead of being copied and pasted as Mata data because it is faster, however none of the matrices are changed in any way, so it should not permanently affect the data.
79
+
80
+ st_view(Y=.,.,tokens(Y_var),"touse") //importing variables vectors to mata
81
+ st_view(X=.,.,tokens(X_var),"touse")
82
+ st_view(lat=.,.,tokens(lat_var),"touse")
83
+ st_view(lon=.,.,tokens(lon_var),"touse")
84
+ st_view(time=.,.,tokens(time_var),"touse")
85
+ st_view(panel=.,.,tokens(panel_var),"touse")
86
+
87
+ k = st_numscalar("k") //importing other parameters
88
+ n = st_numscalar("n")
89
+ b = st_matrix("e(b)") // (estimated coefficients, row vector)
90
+ lag_var = st_local("lagcutoff")
91
+ lag_cutoff = strtoreal(lag_var)
92
+ dist_var = st_local("distcutoff")
93
+ dist_cutoff = strtoreal(dist_var)
94
+
95
+ XeeX = J(k, k, 0) //set variance-covariance matrix equal to zeros
96
+
97
+
98
+ /*--------THIRD, CORRECT VCE FOR SPATIAL CORR-------*/
99
+
100
+ timeUnique = uniqrows(time)
101
+ Ntime = rows(timeUnique) // # of obs. periods
102
+
103
+ for (ti = 1; ti <= Ntime; ti++){
104
+
105
+
106
+
107
+ // 1 if in year ti, 0 otherwise:
108
+
109
+ rows_ti = time:==timeUnique[ti,1]
110
+
111
+ //get subsets of variables for time ti (without changing original matrix)
112
+
113
+ Y1 = select(Y, rows_ti)
114
+ X1 = select(X, rows_ti)
115
+ lat1 = select(lat, rows_ti)
116
+ lon1 = select(lon, rows_ti)
117
+ e1 = Y1 - X1*b'
118
+
119
+ n1 = length(Y1) // # obs for period ti
120
+
121
+ //loop over all observations in period ti
122
+
123
+ for (i = 1; i <=n1; i++){
124
+
125
+
126
+ //----------------------------------------------------------------
127
+ // step a: get non-parametric weight
128
+
129
+ //This is a Euclidean distance scale IN KILOMETERS specific to i
130
+
131
+ lon_scale = cos(lat1[i,1]*pi()/180)*111
132
+ lat_scale = 111
133
+
134
+
135
+ // Distance scales lat and lon degrees differently depending on
136
+ // latitude. The distance here assumes a distortion of Euclidean
137
+ // space around the location of 'i' that is approximately correct for
138
+ // displacements around the location of 'i'
139
+ //
140
+ // Note: 1 deg lat = 111 km
141
+ // 1 deg lon = 111 km * cos(lat)
142
+
143
+ distance_i = ((lat_scale*(lat1[i,1]:-lat1)):^2 + ///
144
+ (lon_scale*(lon1[i,1]:-lon1)):^2):^0.5
145
+
146
+
147
+
148
+ // this sets all observations beyon dist_cutoff to zero, and weights all nearby observations equally [this kernal is isotropic]
149
+
150
+ window_i = distance_i :<= dist_cutoff
151
+
152
+ //----------------------------------------------------------------
153
+ // adjustment for the weights if a "bartlett" kernal is selected as an option
154
+
155
+ if ("`bartlett'"=="bartlett"){
156
+
157
+ // this weights observations as a linear function of distance
158
+ // that is zero at the cutoff distance
159
+
160
+ weight_i = 1:- distance_i:/dist_cutoff
161
+
162
+ window_i = window_i:*weight_i
163
+ }
164
+
165
+
166
+ //----------------------------------------------------------------
167
+ // step b: construct X'e'eX for the given observation
168
+
169
+ XeeXh = ((X1[i,.]'*J(1,n1,1)*e1[i,1]):*(J(k,1,1)*e1':*window_i'))*X1
170
+
171
+ //add each new k x k matrix onto the existing matrix (will be symmetric)
172
+
173
+ XeeX = XeeX + XeeXh
174
+
175
+ } //i
176
+ } // ti
177
+
178
+
179
+
180
+ // -----------------------------------------------------------------
181
+ // generate the VCE for only cross-sectional spatial correlation,
182
+ // return it for comparison
183
+
184
+ invXX = luinv(X'*X) * n
185
+
186
+ XeeX_spatial = XeeX / n
187
+
188
+ V = invXX * XeeX_spatial * invXX / n
189
+
190
+ // Ensures that the matrix is symmetric
191
+ // in theory, it should be already, but it may not be due to rounding errors for large datasets
192
+ V = (V+V')/2
193
+
194
+ st_matrix("V_spatial", V)
195
+
196
+ } // mata
197
+
198
+
199
+ //------------------------------------------------------------------
200
+ // storing old statistics about the estimate so postestimation can be used
201
+
202
+ matrix beta = e(b)
203
+ scalar r2_old = e(r2)
204
+ scalar df_m_old = e(df_m)
205
+ scalar df_r_old = e(df_r)
206
+ scalar rmse_old = e(rmse)
207
+ scalar mss_old = e(mss)
208
+ scalar rss_old = e(rss)
209
+ scalar r2_a_old = e(r2_a)
210
+
211
+ // the row and column names of the new VCE must match the vector b
212
+
213
+ matrix colnames V_spatial = `X'
214
+ matrix rownames V_spatial = `X'
215
+
216
+ // this sets the new estimates as the most recent model
217
+
218
+ ereturn post beta V_spatial, esample(`touse')
219
+
220
+ // then filling back in all the parameters for postestimation
221
+
222
+ ereturn local cmd = "ols_spatial"
223
+
224
+ ereturn scalar N = n_obs
225
+
226
+ ereturn scalar r2 = r2_old
227
+ ereturn scalar df_m = df_m_old
228
+ ereturn scalar df_r = df_r_old
229
+ ereturn scalar rmse = rmse_old
230
+ ereturn scalar mss = mss_old
231
+ ereturn scalar rss = rss_old
232
+ ereturn scalar r2_a = r2_a_old
233
+
234
+ ereturn local title = "Linear regression"
235
+ ereturn local depvar = "`Y'"
236
+ ereturn local predict = "regres_p"
237
+ ereturn local model = "ols"
238
+ ereturn local estat_cmd = "regress_estat"
239
+
240
+ //storing these estimates for comparison to OLS and the HAC estimates
241
+
242
+ estimates store spatial
243
+
244
+
245
+
246
+ /*--------FOURTH, CORRECT VCE FOR SERIAL CORR-------*/
247
+
248
+ mata{
249
+
250
+ panelUnique = uniqrows(panel)
251
+ Npanel = rows(panelUnique) // # of panels
252
+
253
+ for (pi = 1; pi <= Npanel; pi++){
254
+
255
+ // 1 if in panel pi, 0 otherwise:
256
+
257
+ rows_pi = panel:==panelUnique[pi,1]
258
+
259
+ //get subsets of variables for panel pi (without changing original matrix)
260
+
261
+ Y1 = select(Y, rows_pi)
262
+ X1 = select(X, rows_pi)
263
+ time1 = select(time, rows_pi)
264
+ e1 = Y1 - X1*b'
265
+
266
+ n1 = length(Y1) // # obs for panel pi
267
+
268
+ //loop over all observations in panel pi
269
+
270
+ for (t = 1; t <=n1; t++){
271
+
272
+ // ----------------------------------------------------------------
273
+ // step a: get non-parametric weight
274
+
275
+ // this is the weight for Newey-West with a Bartlett kernal
276
+
277
+ //weight = (1:-abs(time1[t,1] :- time1))/(lag_cutoff+1) // correction: need to removing parentheses to compute inter-temporal (6/10/18)
278
+ weight = 1:-abs(time1[t,1] :- time1)/(lag_cutoff+1)
279
+
280
+
281
+ // obs var far enough apart in time are prescribed to have no estimated
282
+ // correlation (Greene recomments lag_cutoff >= T^0.25 {pg 546})
283
+
284
+ window_t = (abs(time1[t,1]:- time1) :<= lag_cutoff) :* weight
285
+
286
+ //this is required so diagonal terms in var-covar matrix are not
287
+ //double counted (since they were counted once above for the spatial
288
+ //correlation estimates:
289
+
290
+ window_t = window_t :* (time1[t,1] :!= time1)
291
+
292
+ // ----------------------------------------------------------------
293
+ // step b: construct X'e'eX for given observation
294
+
295
+ XeeXh = ((X1[t,.]'*J(1,n1,1)*e1[t,1]):*(J(k,1,1)*e1':*window_t'))*X1
296
+
297
+ //add each new k x k matrix onto the existing matrix (will be symmetric)
298
+
299
+ XeeX = XeeX + XeeXh
300
+
301
+ } // t
302
+ } // pi
303
+
304
+
305
+
306
+
307
+ // -----------------------------------------------------------------
308
+ // generate the VCE for x-sectional spatial correlation and serial correlation
309
+
310
+ XeeX_spatial_HAC = XeeX / n
311
+
312
+ V = invXX * XeeX_spatial_HAC * invXX / n
313
+
314
+ // Ensures that the matrix is symmetric
315
+ // in theory, it should be already, but it may not be due to rounding errors for large datasets
316
+ V = (V+V')/2
317
+
318
+ st_matrix("V_spatial_HAC", V)
319
+
320
+ } // mata
321
+
322
+ //------------------------------------------------------------------
323
+ //storing results
324
+
325
+ matrix beta = e(b)
326
+
327
+ // the row and column names of the new VCE must match the vector b
328
+
329
+ matrix colnames V_spatial_HAC = `X'
330
+ matrix rownames V_spatial_HAC = `X'
331
+
332
+ // this sets the new estimates as the most recent model
333
+
334
+ marksample touse // indicator for inclusion in the sample
335
+
336
+ ereturn post beta V_spatial_HAC, esample(`touse')
337
+
338
+ // then filling back in all the parameters for postestimation
339
+
340
+ ereturn local cmd = "ols_spatial_HAC"
341
+
342
+ ereturn scalar N = n_obs
343
+ ereturn scalar r2 = r2_old
344
+ ereturn scalar df_m = df_m_old
345
+ ereturn scalar df_r = df_r_old
346
+ ereturn scalar rmse = rmse_old
347
+ ereturn scalar mss = mss_old
348
+ ereturn scalar rss = rss_old
349
+ ereturn scalar r2_a = r2_a_old
350
+
351
+ ereturn local title = "Linear regression"
352
+ ereturn local depvar = "`Y'"
353
+ ereturn local predict = "regres_p"
354
+ ereturn local model = "ols"
355
+ ereturn local estat_cmd = "regress_estat"
356
+
357
+ //storing these estimates for comparison to OLS and the HAC estimates
358
+
359
+ estimates store spatHAC
360
+
361
+ //------------------------------------------------------------------
362
+ //displaying results
363
+
364
+ disp as txt " "
365
+ disp as txt "OLS REGRESSION"
366
+ disp as txt " "
367
+ disp as txt "SE CORRECTED FOR CROSS-SECTIONAL SPATIAL DEPENDANCE"
368
+ disp as txt " AND PANEL-SPECIFIC SERIAL CORRELATION"
369
+ disp as txt " "
370
+ disp as txt "DEPENDANT VARIABLE: `Y'"
371
+ disp as txt "INDEPENDANT VARIABLES: `X'"
372
+ disp as txt " "
373
+ disp as txt "SPATIAL CORRELATION KERNAL CUTOFF: `distcutoff' KM"
374
+
375
+ if "`bartlett'" == "bartlett" {
376
+ disp as txt "(NOTE: LINEAR BARTLETT WINDOW USED FOR SPATIAL KERNAL)"
377
+ }
378
+
379
+ disp as txt "SERIAL CORRELATION KERNAL CUTOFF: `lagcutoff' PERIODS"
380
+
381
+ ereturn display // standard Stata regression table format
382
+
383
+ // displaying different SE if option selected
384
+
385
+ if "`display'" == "display"{
386
+ disp as txt " "
387
+ disp as txt "STANDARD ERRORS UNDER OLS, WITH SPATIAL CORRECTION AND WITH SPATIAL AND SERIAL CORRECTION:"
388
+ estimates table OLS spatial spatHAC, b(%7.3f) se(%7.3f) t(%7.3f) stats(N r2)
389
+ }
390
+
391
+ if "`star'" == "star"{
392
+ disp as txt " "
393
+ disp as txt "STANDARD ERRORS UNDER OLS, WITH SPATIAL CORRECTION AND WITH SPATIAL AND SERIAL CORRECTION:"
394
+ estimates table OLS spatial spatHAC, b(%7.3f) star(0.10 0.05 0.01)
395
+ }
396
+
397
+ //------------------------------------------------------------------
398
+ // cleaning up Mata environment
399
+
400
+ capture mata mata drop V invXX XeeX XeeXh XeeX_spatial_HAC window_t window_i weight t i ti pi X1 Y1 e1 time1 n1 lat lon lat1 lon1 lat_scale lon_scale rows_ti rows_pi timeUnique panelUnique Ntime Npanel X X_var XeeX_spatial Y Y_var b dist_cutoff dist_var distance_i k lag_cutoff lag_var lat_var lon_var n panel panel_var time time_var weight_i
401
+
402
+ /*
403
+ if "`bartlett'" == "bartlett" {
404
+ capture mata mata drop weight_i
405
+ }
406
+ */
407
+
408
+ end
110/replication_package/replication/ado/personal/reg2hdfespatial.ado ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ capture program drop reg2hdfespatial
2
+ *! Thiemo Fetzer 4/2015: WRAPPER PROGRAM TO ESTIMATE SPATIAL HAC FOR OLS REGRESSION MODELS WITH HIGH DIMENSIONAL FIXED EFFECTS
3
+ *! The function uses the reg2hdfe procedure to demean the data by the time- and panel-variable you specify
4
+ *! This ensures that you do not compute large variance covariance matrices to compute
5
+ *! Spatial HAC errors for coefficients you do not actually care about.
6
+ *! Updates available on http://www.trfetzer.com
7
+ *! Please email me in case you find any bugs or have suggestions for improvement.
8
+ *! Please cite: Fetzer, T. (2014) "Can Workfare Programs Moderate Violence? Evidence from India", STICERD Working Paper.
9
+ *! Also credit Sol Hsiang.
10
+ *! Hsiang, S. M. (2010). Temperatures and cyclones strongly associated with economic production in the Caribbean and Central America. PNAS, 107(35), 15367–72.
11
+ *! The Use of the function is simple
12
+ *! reg2hdfespatial Yvar Xvarlist, lat(latvar) lon(lonvar) Timevar(tvar) Panelvar(pvar) [DISTcutoff(#) LAGcutoff(#) bartlett DISPlay star dropvar demean altfetime(varname) altfepanel(varname)]
13
+ *!
14
+ *!
15
+ *! You can also specify other fixed effects:
16
+ *! reg2hdfespatial Yvar Xvarlist ,timevar(year) panelvar(district) altfetime(regionyear) lat(y) lon(x) distcutoff(500) lagcutoff(20)
17
+ *!
18
+ *! here I specify the time variable as the year, but I demean the data first
19
+ *! by region x year fixed effects.
20
+ *! This turns out to matter as the OLS_Spatial_HAC for the autocorrelation correction which you may want
21
+ *! to be done at a level different from the level at which you have the time fixed effects specified.
22
+ /*-----------------------------------------------------------------------------
23
+
24
+ Syntax:
25
+
26
+ reg2hdfespatial Yvar Xvarlist, lat(latvar) lon(lonvar) Timevar(tvar) Panelvar(pvar) [DISTcutoff(#) LAGcutoff(#) bartlett DISPlay star dropvar demean altfetime(varname) altfepanel(varname)]
27
+
28
+ -----------------------------------------------------------------------------*/
29
+
30
+ program reg2hdfespatial, eclass byable(recall)
31
+ //version 9.2
32
+ version 11
33
+ syntax varlist(ts fv min=2) [if] [in], ///
34
+ lat(varname numeric) lon(varname numeric) ///
35
+ Timevar(varname numeric) Panelvar(varname numeric) [LAGcutoff(integer 0) DISTcutoff(real 1) ///
36
+ DISPlay star bartlett dropvar altfetime(varname) altfepanel(varname) ]
37
+
38
+ /*--------PARSING COMMANDS AND SETUP-------*/
39
+
40
+ preserve
41
+ if "`if'"~="" {
42
+ qui keep `if'
43
+ }
44
+
45
+
46
+ capture drop touse
47
+ marksample touse // indicator for inclusion in the sample
48
+ gen touse = `touse'
49
+
50
+ *keep if touse
51
+ //parsing variables
52
+ loc Y = word("`varlist'",1)
53
+
54
+ loc listing "`varlist'"
55
+
56
+
57
+ loc X ""
58
+ scalar k_variables = 0
59
+
60
+ //make sure that Y is not included in the other_var list
61
+ foreach i of loc listing {
62
+ if "`i'" ~= "`Y'"{
63
+ loc X "`X' `i'"
64
+ scalar k_variables = k_variables + 1 // # indep variables
65
+
66
+ }
67
+ }
68
+ local wdir `c(pwd)'
69
+
70
+ tmpdir returns r(tmpdir):
71
+ local tdir `r(tmpdir)'
72
+
73
+
74
+ **clear temp folder of existing files
75
+ qui cd "`tdir'"
76
+ local tempfiles : dir . files "*.dta"
77
+ foreach f in `tempfiles' {
78
+ erase `f'
79
+ }
80
+
81
+ quietly {
82
+ if("`altfepanel'" !="" & "`altfetime'" !="") {
83
+ di "CASE 1"
84
+ reg2hdfe `Y' `X' `lat' `lon' `timevar' `panelvar' , id1(`altfepanel') id2(`altfetime') out("`tdir'") noregress
85
+ loc iteratevarlist "`Y' `X' `lat' `lon' `timevar' `panelvar'"
86
+ reg2hdfe `Y' `X' , id1(`altfepanel') id2(`altfetime')
87
+ }
88
+ if("`altfepanel'" =="" & "`altfetime'" !="") {
89
+ di "CASE 2"
90
+
91
+ reg2hdfe `Y' `X' `lat' `lon' `timevar' , id1(`panelvar') id2(`altfetime') out("`tdir'") noregress
92
+ loc iteratevarlist "`Y' `X' `lat' `lon' `timevar' "
93
+
94
+ reg2hdfe `Y' `X' , id1(`panelvar') id2(`altfetime')
95
+ }
96
+ if("`altfepanel'" !="" & "`altfetime'" =="") {
97
+ di "CASE 3"
98
+
99
+ reg2hdfe `Y' `X' `lat' `lon' `panelvar' , id1(`altfepanel') id2(`timevar') out("`tdir'") noregress
100
+ reg2hdfe `Y' `X' , id1(`altfepanel') id2(`timevar')
101
+ loc iteratevarlist "`Y' `X' `lat' `lon' `panelvar'"
102
+ }
103
+ if("`altfepanel'" =="" & "`altfetime'" =="") {
104
+ di "CASE 4"
105
+ reg2hdfe `Y' `X' `lat' `lon' , id1(`panelvar') id2(`timevar') out("`tdir'") noregress
106
+ loc iteratevarlist "`Y' `X' `lat' `lon'"
107
+ reg2hdfe `Y' `X' , id1(`panelvar') id2(`timevar')
108
+ }
109
+
110
+ foreach var of varlist `X' {
111
+ lincom `var'
112
+ if `r(se)' != 0 {
113
+ loc newVarList "`newVarList' `var'"
114
+ scalar k_variables = k_variables + 1
115
+ }
116
+ }
117
+
118
+ loc XX "`newVarList'"
119
+
120
+
121
+ /* From reg2hdfe.ado */
122
+ tempfile tmp1 tmp2 tmp3 readdata
123
+
124
+ use _ids, clear
125
+ sort __uid
126
+ qui save "`tmp1'", replace
127
+ if "`cluster'"!="" {
128
+ merge __uid using _clustervar
129
+ if r(min)<r(max) {
130
+ di "Fatal Error"
131
+ error 198
132
+ }
133
+ drop _merge
134
+ sort __uid
135
+ rename __clustervar `clustervar'
136
+ qui save "`tmp1'", replace
137
+ }
138
+
139
+
140
+ * Now read the original variables
141
+ foreach var in `iteratevarlist' {
142
+ merge __uid using _`var'
143
+ sum _merge, meanonly
144
+ if r(min)<r(max) {
145
+ di "Fatal Error"
146
+ error 198
147
+ }
148
+ tab _merge
149
+ drop _merge
150
+ drop __fe2*
151
+ drop __t_*
152
+ sort __uid
153
+ qui save "`tmp2'", replace
154
+ }
155
+ foreach var in `iteratevarlist' {
156
+ rename __o_`var' `var'
157
+ }
158
+
159
+
160
+ tempvar yy sy
161
+ gen double `yy'=(`depvar'-r(mean))^2
162
+ gen double `sy'=sum(`yy')
163
+ local tss=`sy'[_N]
164
+ drop `yy' `sy'
165
+ qui save "`readdata'", replace
166
+ use `tmp1', clear
167
+ foreach var in `iteratevarlist' {
168
+ merge 1:1 __uid using _`var'
169
+ sum _merge, meanonly
170
+ if r(min)<r(max) {
171
+ di "Fatal Error."
172
+ error 198
173
+ }
174
+
175
+ drop _merge
176
+ }
177
+
178
+ drop __fe2*
179
+ rename __o_`lon' `lon'
180
+ rename __o_`lat' `lat'
181
+ if("`altfepanel'" !="" ) {
182
+ rename __o_`panelvar' `panelvar'
183
+ }
184
+ if("`altfetime'" !="" ) {
185
+ rename __o_`timevar' `timevar'
186
+ }
187
+
188
+ drop __o_*
189
+ sort __uid
190
+ qui save "`tmp3'", replace
191
+
192
+ foreach var in `Y' `X' {
193
+ rename __t_`var' `var'
194
+ }
195
+
196
+ }
197
+ ols_spatial_HAC `Y' `XX', lat(`lat') lon(`lon') timevar(`timevar') panelvar(`panelvar') lagcutoff(`lagcutoff') distcutoff(`distcutoff') bartlett
198
+
199
+ cd "`wdir'"
200
+ end
201
+
202
+
110/replication_package/replication/ado/plus/_/_eststo.ado ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *! version 1.0.4 09nov2007 Ben Jann
2
+
3
+ program define _eststo, byable(onecall)
4
+ local caller : di _caller()
5
+ version 8.2
6
+ if "`_byvars'"!="" local by "by `_byvars'`_byrc0' : "
7
+ if inlist(`"`1'"',"clear","dir","drop") {
8
+ version `caller': `by'eststo `0'
9
+ }
10
+ else {
11
+ capt _on_colon_parse `0'
12
+ if !_rc {
13
+ local command `"`s(after)'"'
14
+ if `"`command'"'!="" {
15
+ local command `":`command'"'
16
+ }
17
+ local 0 `"`s(before)'"'
18
+ }
19
+ syntax [anything] [, Esample * ]
20
+ if `"`esample'"'=="" {
21
+ local options `"noesample `options'"'
22
+ }
23
+ if `"`options'"'!="" {
24
+ local options `", `options'"'
25
+ }
26
+ version `caller': `by'eststo `anything'`options' `command'
27
+ }
28
+ end
110/replication_package/replication/ado/plus/_/_eststo.hlp ADDED
@@ -0,0 +1 @@
 
 
1
+ .h eststo
110/replication_package/replication/ado/plus/b/binscatter.ado ADDED
@@ -0,0 +1,1048 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *! version 7.02 24nov2013 Michael Stepner, [email protected]
2
+
3
+ /* CC0 license information:
4
+ To the extent possible under law, the author has dedicated all copyright and related and neighboring rights
5
+ to this software to the public domain worldwide. This software is distributed without any warranty.
6
+
7
+ This code is licensed under the CC0 1.0 Universal license. The full legal text as well as a
8
+ human-readable summary can be accessed at http://creativecommons.org/publicdomain/zero/1.0/
9
+ */
10
+
11
+ * Why did I include a formal license? Jeff Atwood gives good reasons: http://www.codinghorror.com/blog/2007/04/pick-a-license-any-license.html
12
+
13
+
14
+ program define binscatter, eclass sortpreserve
15
+ version 12.1
16
+
17
+ syntax varlist(min=2 numeric) [if] [in] [aweight fweight], [by(varname) ///
18
+ Nquantiles(integer 20) GENxq(name) discrete xq(varname numeric) MEDians ///
19
+ CONTROLs(varlist numeric ts fv) absorb(varname) noAddmean ///
20
+ LINEtype(string) rd(numlist ascending) reportreg ///
21
+ COLors(string) MColors(string) LColors(string) Msymbols(string) ///
22
+ savegraph(string) savedata(string) replace ///
23
+ nofastxtile randvar(varname numeric) randcut(real 1) randn(integer -1) ///
24
+ /* LEGACY OPTIONS */ nbins(integer 20) create_xq x_q(varname numeric) symbols(string) method(string) unique(string) ///
25
+ *]
26
+
27
+ set more off
28
+
29
+ * Create convenient weight local
30
+ if ("`weight'"!="") local wt [`weight'`exp']
31
+
32
+ ***** Begin legacy option compatibility code
33
+
34
+ if (`nbins'!=20) {
35
+ if (`nquantiles'!=20) {
36
+ di as error "Cannot specify both nquantiles() and nbins(): both are the same option, nbins is supported only for backward compatibility."
37
+ exit
38
+ }
39
+ di as text "NOTE: legacy option nbins() has been renamed nquantiles(), and is supported only for backward compatibility."
40
+ local nquantiles=`nbins'
41
+ }
42
+
43
+ if ("`create_xq'"!="") {
44
+ if ("`genxq'"!="") {
45
+ di as error "Cannot specify both genxq() and create_xq: both are the same option, create_xq is supported only for backward compatibility."
46
+ exit
47
+ }
48
+ di as text "NOTE: legacy option create_xq has been renamed genxq(), and is supported only for backward compatibility."
49
+ local genxq="q_"+word("`varlist'",-1)
50
+ }
51
+
52
+ if ("`x_q'"!="") {
53
+ if ("`xq'"!="") {
54
+ di as error "Cannot specify both xq() and x_q(): both are the same option, x_q() is supported only for backward compatibility."
55
+ exit
56
+ }
57
+ di as text "NOTE: legacy option x_q() has been renamed xq(), and is supported only for backward compatibility."
58
+ local xq `x_q'
59
+ }
60
+
61
+ if ("`symbols'"!="") {
62
+ if ("`msymbols'"!="") {
63
+ di as error "Cannot specify both msymbols() and symbols(): both are the same option, symbols() is supported only for backward compatibility."
64
+ exit
65
+ }
66
+ di as text "NOTE: legacy option symbols() has been renamed msymbols(), and is supported only for backward compatibility."
67
+ local msymbols `symbols'
68
+ }
69
+
70
+ if ("`linetype'"=="noline") {
71
+ di as text "NOTE: legacy line type 'noline' has been renamed 'none', and is supported only for backward compatibility."
72
+ local linetype none
73
+ }
74
+
75
+ if ("`method'"!="") {
76
+ di as text "NOTE: method() is no longer a recognized option, and will be ignored. binscatter now always uses the fastest method without a need for two instances"
77
+ }
78
+
79
+ if ("`unique'"!="") {
80
+ di as text "NOTE: unique() is no longer a recognized option, and will be ignored. binscatter now considers the x-variable discrete if it has fewer unique values than nquantiles()"
81
+ }
82
+
83
+ ***** End legacy option capatibility code
84
+
85
+ *** Perform checks
86
+
87
+ * Set default linetype and check valid
88
+ if ("`linetype'"=="") local linetype lfit
89
+ else if !inlist("`linetype'","connect","lfit","qfit","none") {
90
+ di as error "linetype() must either be connect, lfit, qfit, or none"
91
+ exit
92
+ }
93
+
94
+ * Check that nofastxtile isn't combined with fastxtile-only options
95
+ if "`fastxtile'"=="nofastxtile" & ("`randvar'"!="" | `randcut'!=1 | `randn'!=-1) {
96
+ di as error "Cannot combine randvar, randcut or randn with nofastxtile"
97
+ exit
98
+ }
99
+
100
+ * Misc checks
101
+ if ("`genxq'"!="" & ("`xq'"!="" | "`discrete'"!="")) | ("`xq'"!="" & "`discrete'"!="") {
102
+ di as error "Cannot specify more than one of genxq(), xq(), and discrete simultaneously."
103
+ exit
104
+ }
105
+ if ("`genxq'"!="") confirm new variable `genxq'
106
+ if ("`xq'"!="") {
107
+ capture assert `xq'==int(`xq') & `xq'>0
108
+ if _rc!=0 {
109
+ di as error "xq() must contain only positive integers."
110
+ exit
111
+ }
112
+
113
+ if ("`controls'`absorb'"!="") di as text "warning: xq() is specified in combination with controls() or absorb(). note that binning takes places after residualization, so the xq variable should contain bins of the residuals."
114
+ }
115
+ if `nquantiles'!=20 & ("`xq'"!="" | "`discrete'"!="") {
116
+ di as error "Cannot specify nquantiles in combination with discrete or an xq variable."
117
+ exit
118
+ }
119
+ if "`reportreg'"!="" & !inlist("`linetype'","lfit","qfit") {
120
+ di as error "Cannot specify 'reportreg' when no fit line is being created."
121
+ exit
122
+ }
123
+ if "`replace'"=="" {
124
+ if `"`savegraph'"'!="" {
125
+ if regexm(`"`savegraph'"',"\.[a-zA-Z0-9]+$") confirm new file `"`savegraph'"'
126
+ else confirm new file `"`savegraph'.gph"'
127
+ }
128
+ if `"`savedata'"'!="" {
129
+ confirm new file `"`savedata'.csv"'
130
+ confirm new file `"`savedata'.do"'
131
+ }
132
+ }
133
+
134
+ * Mark sample (reflects the if/in conditions, and includes only nonmissing observations)
135
+ marksample touse
136
+ markout `touse' `by' `xq' `controls' `absorb', strok
137
+ qui count if `touse'
138
+ local samplesize=r(N)
139
+ local touse_first=_N-`samplesize'+1
140
+ local touse_last=_N
141
+
142
+ * Parse varlist into y-vars and x-var
143
+ local x_var=word("`varlist'",-1)
144
+ local y_vars=regexr("`varlist'"," `x_var'$","")
145
+ local ynum=wordcount("`y_vars'")
146
+
147
+ * Check number of unique byvals & create local storing byvals
148
+ if "`by'"!="" {
149
+ local byvarname `by'
150
+
151
+ capture confirm numeric variable `by'
152
+ if _rc {
153
+ * by-variable is string => generate a numeric version
154
+ tempvar by
155
+ tempname bylabel
156
+ egen `by'=group(`byvarname'), lname(`bylabel')
157
+ }
158
+
159
+ local bylabel `:value label `by'' /*catch value labels for numeric by-vars too*/
160
+
161
+ tempname byvalmatrix
162
+ qui tab `by' if `touse', nofreq matrow(`byvalmatrix')
163
+
164
+ local bynum=r(r)
165
+ forvalues i=1/`bynum' {
166
+ local byvals `byvals' `=`byvalmatrix'[`i',1]'
167
+ }
168
+ }
169
+ else local bynum=1
170
+
171
+
172
+ ****** Create residuals ******
173
+
174
+ if (`"`controls'`absorb'"'!="") quietly {
175
+
176
+ * Parse absorb to define the type of regression to be used
177
+ if `"`absorb'"'!="" {
178
+ local regtype "areg"
179
+ local absorb "absorb(`absorb')"
180
+ }
181
+ else {
182
+ local regtype "reg"
183
+ }
184
+
185
+ * Generate residuals
186
+
187
+ local firstloop=1
188
+ foreach var of varlist `x_var' `y_vars' {
189
+ tempvar residvar
190
+ `regtype' `var' `controls' `wt' if `touse', `absorb'
191
+ predict `residvar' if e(sample), residuals
192
+ if ("`addmean'"!="noaddmean") {
193
+ summarize `var' `wt' if `touse', meanonly
194
+ replace `residvar'=`residvar'+r(mean)
195
+ }
196
+
197
+ label variable `residvar' "`var'"
198
+ if `firstloop'==1 {
199
+ local x_r `residvar'
200
+ local firstloop=0
201
+ }
202
+ else local y_vars_r `y_vars_r' `residvar'
203
+ }
204
+
205
+ }
206
+ else { /*absorb and controls both empty, no need for regression*/
207
+ local x_r `x_var'
208
+ local y_vars_r `y_vars'
209
+ }
210
+
211
+
212
+ ****** Regressions for fit lines ******
213
+
214
+ if ("`reportreg'"=="") local reg_verbosity "quietly"
215
+
216
+ if inlist("`linetype'","lfit","qfit") `reg_verbosity' {
217
+
218
+ * If doing a quadratic fit, generate a quadratic term in x
219
+ if "`linetype'"=="qfit" {
220
+ tempvar x_r2
221
+ gen `x_r2'=`x_r'^2
222
+ }
223
+
224
+ * Create matrices to hold regression results
225
+ tempname e_b_temp
226
+ forvalues i=1/`ynum' {
227
+ tempname y`i'_coefs
228
+ }
229
+
230
+ * LOOP over by-vars
231
+ local counter_by=1
232
+ if ("`by'"=="") local noby="noby"
233
+ foreach byval in `byvals' `noby' {
234
+
235
+ * LOOP over rd intervals
236
+ tokenize "`rd'"
237
+ local counter_rd=1
238
+
239
+ while ("`1'"!="" | `counter_rd'==1) {
240
+
241
+ * display text headers
242
+ if "`reportreg'"!="" {
243
+ di "{txt}{hline}"
244
+ if ("`by'"!="") {
245
+ if ("`bylabel'"=="") di "-> `byvarname' = `byval'"
246
+ else {
247
+ di "-> `byvarname' = `: label `bylabel' `byval''"
248
+ }
249
+ }
250
+ if ("`rd'"!="") {
251
+ if (`counter_rd'==1) di "RD: `x_var'<=`1'"
252
+ else if ("`2'"!="") di "RD: `x_var'>`1' & `x_var'<=`2'"
253
+ else di "RD: `x_var'>`1'"
254
+ }
255
+ }
256
+
257
+ * set conditions on reg
258
+ local conds `touse'
259
+
260
+ if ("`by'"!="" ) local conds `conds' & `by'==`byval'
261
+
262
+ if ("`rd'"!="") {
263
+ if (`counter_rd'==1) local conds `conds' & `x_r'<=`1'
264
+ else if ("`2'"!="") local conds `conds' & `x_r'>`1' & `x_r'<=`2'
265
+ else local conds `conds' & `x_r'>`1'
266
+ }
267
+
268
+ * LOOP over y-vars
269
+ local counter_depvar=1
270
+ foreach depvar of varlist `y_vars_r' {
271
+
272
+ * display text headers
273
+ if (`ynum'>1) {
274
+ if ("`controls'`absorb'"!="") local depvar_name : var label `depvar'
275
+ else local depvar_name `depvar'
276
+ di as text "{bf:y_var = `depvar_name'}"
277
+ }
278
+
279
+ * perform regression
280
+ if ("`reg_verbosity'"=="quietly") capture reg `depvar' `x_r2' `x_r' `wt' if `conds'
281
+ else capture noisily reg `depvar' `x_r2' `x_r' `wt' if `conds'
282
+
283
+ * store results
284
+ if (_rc==0) matrix e_b_temp=e(b)
285
+ else if (_rc==2000) {
286
+ if ("`reg_verbosity'"=="quietly") di as error "no observations for one of the fit lines. add 'reportreg' for more info."
287
+
288
+ if ("`linetype'"=="lfit") matrix e_b_temp=.,.
289
+ else /*("`linetype'"=="qfit")*/ matrix e_b_temp=.,.,.
290
+ }
291
+ else {
292
+ error _rc
293
+ exit _rc
294
+ }
295
+
296
+ * relabel matrix row
297
+ if ("`by'"!="") matrix roweq e_b_temp = "by`counter_by'"
298
+ if ("`rd'"!="") matrix rownames e_b_temp = "rd`counter_rd'"
299
+ else matrix rownames e_b_temp = "="
300
+
301
+ * save to y_var matrix
302
+ if (`counter_by'==1 & `counter_rd'==1) matrix `y`counter_depvar'_coefs'=e_b_temp
303
+ else matrix `y`counter_depvar'_coefs'=`y`counter_depvar'_coefs' \ e_b_temp
304
+
305
+ * increment depvar counter
306
+ local ++counter_depvar
307
+ }
308
+
309
+ * increment rd counter
310
+ if (`counter_rd'!=1) mac shift
311
+ local ++counter_rd
312
+
313
+ }
314
+
315
+ * increment by counter
316
+ local ++counter_by
317
+
318
+ }
319
+
320
+ * relabel matrix column names
321
+ forvalues i=1/`ynum' {
322
+ if ("`linetype'"=="lfit") matrix colnames `y`i'_coefs' = "`x_var'" "_cons"
323
+ else if ("`linetype'"=="qfit") matrix colnames `y`i'_coefs' = "`x_var'^2" "`x_var'" "_cons"
324
+ }
325
+
326
+ }
327
+
328
+ ******* Define the bins *******
329
+
330
+ * Specify and/or create the xq var, as necessary
331
+ if "`xq'"=="" {
332
+
333
+ if !(`touse_first'==1 & word("`:sortedby'",1)=="`x_r'") sort `touse' `x_r'
334
+
335
+ if "`discrete'"=="" { /* xq() and discrete are not specified */
336
+
337
+ * Check whether the number of unique values > nquantiles, or <= nquantiles
338
+ capture mata: characterize_unique_vals_sorted("`x_r'",`touse_first',`touse_last',`nquantiles')
339
+
340
+ if (_rc==0) { /* number of unique values <= nquantiles, set to discrete */
341
+ local discrete discrete
342
+ if ("`genxq'"!="") di as text `"note: the x-variable has fewer unique values than the number of bins specified (`nquantiles'). It will therefore be treated as discrete, and genxq() will be ignored"'
343
+
344
+ local xq `x_r'
345
+ local nquantiles=r(r)
346
+ if ("`by'"=="") {
347
+ tempname xq_boundaries xq_values
348
+ matrix `xq_boundaries'=r(boundaries)
349
+ matrix `xq_values'=r(values)
350
+ }
351
+ }
352
+ else if (_rc==134) { /* number of unique values > nquantiles, perform binning */
353
+ if ("`genxq'"!="") local xq `genxq'
354
+ else tempvar xq
355
+
356
+ if ("`fastxtile'"!="nofastxtile") fastxtile `xq' = `x_r' `wt' in `touse_first'/`touse_last', nq(`nquantiles') randvar(`randvar') randcut(`randcut') randn(`randn')
357
+ else xtile `xq' = `x_r' `wt' in `touse_first'/`touse_last', nq(`nquantiles')
358
+
359
+ if ("`by'"=="") {
360
+ mata: characterize_unique_vals_sorted("`xq'",`touse_first',`touse_last',`nquantiles')
361
+
362
+ if (r(r)!=`nquantiles') {
363
+ di as text "warning: nquantiles(`nquantiles') was specified, but only `r(r)' were generated. see help file under nquantiles() for explanation."
364
+ local nquantiles=r(r)
365
+ }
366
+
367
+ tempname xq_boundaries xq_values
368
+ matrix `xq_boundaries'=r(boundaries)
369
+ matrix `xq_values'=r(values)
370
+ }
371
+ }
372
+ else {
373
+ error _rc
374
+ }
375
+
376
+ }
377
+
378
+ else { /* discrete is specified, xq() & genxq() are not */
379
+
380
+ if ("`controls'`absorb'"!="") di as text "warning: discrete is specified in combination with controls() or absorb(). note that binning takes places after residualization, so the residualized x-variable may contain many more unique values."
381
+
382
+ capture mata: characterize_unique_vals_sorted("`x_r'",`touse_first',`touse_last',`=`samplesize'/2')
383
+
384
+ if (_rc==0) {
385
+ local xq `x_r'
386
+ local nquantiles=r(r)
387
+ if ("`by'"=="") {
388
+ tempname xq_boundaries xq_values
389
+ matrix `xq_boundaries'=r(boundaries)
390
+ matrix `xq_values'=r(values)
391
+ }
392
+ }
393
+ else if (_rc==134) {
394
+ di as error "discrete specified, but number of unique values is > (sample size/2)"
395
+ exit 134
396
+ }
397
+ else {
398
+ error _rc
399
+ }
400
+ }
401
+ }
402
+ else {
403
+
404
+ if !(`touse_first'==1 & word("`:sortedby'",1)=="`xq'") sort `touse' `xq'
405
+
406
+ * set nquantiles & boundaries
407
+ mata: characterize_unique_vals_sorted("`xq'",`touse_first',`touse_last',`=`samplesize'/2')
408
+
409
+ if (_rc==0) {
410
+ local nquantiles=r(r)
411
+ if ("`by'"=="") {
412
+ tempname xq_boundaries xq_values
413
+ matrix `xq_boundaries'=r(boundaries)
414
+ matrix `xq_values'=r(values)
415
+ }
416
+ }
417
+ else if (_rc==134) {
418
+ di as error "discrete specified, but number of unique values is > (sample size/2)"
419
+ exit 134
420
+ }
421
+ else {
422
+ error _rc
423
+ }
424
+ }
425
+
426
+ ********** Compute scatter points **********
427
+
428
+ if ("`by'"!="") {
429
+ sort `touse' `by' `xq'
430
+ tempname by_boundaries
431
+ mata: characterize_unique_vals_sorted("`by'",`touse_first',`touse_last',`bynum')
432
+ matrix `by_boundaries'=r(boundaries)
433
+ }
434
+
435
+ forvalues b=1/`bynum' {
436
+ if ("`by'"!="") {
437
+ mata: characterize_unique_vals_sorted("`xq'",`=`by_boundaries'[`b',1]',`=`by_boundaries'[`b',2]',`nquantiles')
438
+ tempname xq_boundaries xq_values
439
+ matrix `xq_boundaries'=r(boundaries)
440
+ matrix `xq_values'=r(values)
441
+ }
442
+ /* otherwise xq_boundaries and xq_values are defined above in the binning code block */
443
+
444
+ * Define x-means
445
+ tempname xbin_means
446
+ if ("`discrete'"=="discrete") {
447
+ matrix `xbin_means'=`xq_values'
448
+ }
449
+ else {
450
+ means_in_boundaries `x_r' `wt', bounds(`xq_boundaries') `medians'
451
+ matrix `xbin_means'=r(means)
452
+ }
453
+
454
+ * LOOP over y-vars to define y-means
455
+ local counter_depvar=0
456
+ foreach depvar of varlist `y_vars_r' {
457
+ local ++counter_depvar
458
+
459
+ means_in_boundaries `depvar' `wt', bounds(`xq_boundaries') `medians'
460
+
461
+ * store to matrix
462
+ if (`b'==1) {
463
+ tempname y`counter_depvar'_scatterpts
464
+ matrix `y`counter_depvar'_scatterpts' = `xbin_means',r(means)
465
+ }
466
+ else {
467
+ * make matrices conformable before right appending
468
+ local rowdiff=rowsof(`y`counter_depvar'_scatterpts')-rowsof(`xbin_means')
469
+ if (`rowdiff'==0) matrix `y`counter_depvar'_scatterpts' = `y`counter_depvar'_scatterpts',`xbin_means',r(means)
470
+ else if (`rowdiff'>0) matrix `y`counter_depvar'_scatterpts' = `y`counter_depvar'_scatterpts', ( (`xbin_means',r(means)) \ J(`rowdiff',2,.) )
471
+ else /*(`rowdiff'<0)*/ matrix `y`counter_depvar'_scatterpts' = ( `y`counter_depvar'_scatterpts' \ J(-`rowdiff',colsof(`y`counter_depvar'_scatterpts'),.) ) ,`xbin_means',r(means)
472
+ }
473
+ }
474
+ }
475
+
476
+ *********** Perform Graphing ***********
477
+
478
+ * If rd is specified, prepare xline parameters
479
+ if "`rd'"!="" {
480
+ foreach xval in "`rd'" {
481
+ local xlines `xlines' xline(`xval', lpattern(dash) lcolor(gs8))
482
+ }
483
+ }
484
+
485
+ * Fill colors if missing
486
+ if `"`colors'"'=="" local colors ///
487
+ navy maroon forest_green dkorange teal cranberry lavender ///
488
+ khaki sienna emidblue emerald brown erose gold bluishgray ///
489
+ /* lime magenta cyan pink blue */
490
+ if `"`mcolors'"'=="" {
491
+ if (`ynum'==1 & `bynum'==1 & "`linetype'"!="connect") local mcolors `: word 1 of `colors''
492
+ else local mcolors `colors'
493
+ }
494
+ if `"`lcolors'"'=="" {
495
+ if (`ynum'==1 & `bynum'==1 & "`linetype'"!="connect") local lcolors `: word 2 of `colors''
496
+ else local lcolors `colors'
497
+ }
498
+ local num_mcolor=wordcount(`"`mcolors'"')
499
+ local num_lcolor=wordcount(`"`lcolors'"')
500
+
501
+
502
+ * Prepare connect & msymbol options
503
+ if ("`linetype'"=="connect") local connect "c(l)"
504
+ if "`msymbols'"!="" {
505
+ local symbol_prefix "msymbol("
506
+ local symbol_suffix ")"
507
+ }
508
+
509
+ *** Prepare scatters
510
+
511
+ * c indexes which color is to be used
512
+ local c=0
513
+
514
+ local counter_series=0
515
+
516
+ * LOOP over by-vars
517
+ local counter_by=0
518
+ if ("`by'"=="") local noby="noby"
519
+ foreach byval in `byvals' `noby' {
520
+ local ++counter_by
521
+
522
+ local xind=`counter_by'*2-1
523
+ local yind=`counter_by'*2
524
+
525
+ * LOOP over y-vars
526
+ local counter_depvar=0
527
+ foreach depvar of varlist `y_vars' {
528
+ local ++counter_depvar
529
+ local ++c
530
+
531
+ * LOOP over rows (each row contains a coordinate pair)
532
+ local row=1
533
+ local xval=`y`counter_depvar'_scatterpts'[`row',`xind']
534
+ local yval=`y`counter_depvar'_scatterpts'[`row',`yind']
535
+
536
+ if !missing(`xval',`yval') {
537
+ local ++counter_series
538
+ local scatters `scatters' (scatteri
539
+ if ("`savedata'"!="") {
540
+ if ("`by'"=="") local savedata_scatters `savedata_scatters' (scatter `depvar' `x_var'
541
+ else local savedata_scatters `savedata_scatters' (scatter `depvar'_by`counter_by' `x_var'_by`counter_by'
542
+ }
543
+ }
544
+ else {
545
+ * skip the rest of this loop iteration
546
+ continue
547
+ }
548
+
549
+ while (`xval'!=. & `yval'!=.) {
550
+ local scatters `scatters' `yval' `xval'
551
+
552
+ local ++row
553
+ local xval=`y`counter_depvar'_scatterpts'[`row',`xind']
554
+ local yval=`y`counter_depvar'_scatterpts'[`row',`yind']
555
+ }
556
+
557
+ * Add options
558
+ local scatter_options `connect' mcolor(`: word `c' of `mcolors'') lcolor(`: word `c' of `lcolors'') `symbol_prefix'`: word `c' of `msymbols''`symbol_suffix'
559
+ local scatters `scatters', `scatter_options')
560
+ if ("`savedata'"!="") local savedata_scatters `savedata_scatters', `scatter_options')
561
+
562
+
563
+ * Add legend
564
+ if "`by'"=="" {
565
+ if (`ynum'==1) local legend_labels off
566
+ else local legend_labels `legend_labels' lab(`counter_series' `depvar')
567
+ }
568
+ else {
569
+ if ("`bylabel'"=="") local byvalname=`byval'
570
+ else {
571
+ local byvalname `: label `bylabel' `byval''
572
+ }
573
+
574
+ if (`ynum'==1) local legend_labels `legend_labels' lab(`counter_series' `byvarname'=`byvalname')
575
+ else local legend_labels `legend_labels' lab(`counter_series' `depvar': `byvarname'=`byvalname')
576
+ }
577
+ if ("`by'"!="" | `ynum'>1) local order `order' `counter_series'
578
+
579
+ }
580
+
581
+ }
582
+
583
+ *** Fit lines
584
+
585
+ if inlist(`"`linetype'"',"lfit","qfit") {
586
+
587
+ * c indexes which color is to be used
588
+ local c=0
589
+
590
+ local rdnum=wordcount("`rd'")+1
591
+
592
+ tempname fitline_bounds
593
+ if ("`rd'"=="") matrix `fitline_bounds'=.,.
594
+ else matrix `fitline_bounds'=.,`=subinstr("`rd'"," ",",",.)',.
595
+
596
+ * LOOP over by-vars
597
+ local counter_by=0
598
+ if ("`by'"=="") local noby="noby"
599
+ foreach byval in `byvals' `noby' {
600
+ local ++counter_by
601
+
602
+ ** Set the column for the x-coords in the scatterpts matrix
603
+ local xind=`counter_by'*2-1
604
+
605
+ * Set the row to start seeking from
606
+ * note: each time we seek a coeff, it should be from row (rd_num)(counter_by-1)+counter_rd
607
+ local row0=( `rdnum' ) * (`counter_by' - 1)
608
+
609
+
610
+ * LOOP over y-vars
611
+ local counter_depvar=0
612
+ foreach depvar of varlist `y_vars_r' {
613
+ local ++counter_depvar
614
+ local ++c
615
+
616
+ * Find lower and upper bounds for the fit line
617
+ matrix `fitline_bounds'[1,1]=`y`counter_depvar'_scatterpts'[1,`xind']
618
+
619
+ local fitline_ub_rindex=`nquantiles'
620
+ local fitline_ub=.
621
+ while `fitline_ub'==. {
622
+ local fitline_ub=`y`counter_depvar'_scatterpts'[`fitline_ub_rindex',`xind']
623
+ local --fitline_ub_rindex
624
+ }
625
+ matrix `fitline_bounds'[1,`rdnum'+1]=`fitline_ub'
626
+
627
+ * LOOP over rd intervals
628
+ forvalues counter_rd=1/`rdnum' {
629
+
630
+ if (`"`linetype'"'=="lfit") {
631
+ local coef_quad=0
632
+ local coef_lin=`y`counter_depvar'_coefs'[`row0'+`counter_rd',1]
633
+ local coef_cons=`y`counter_depvar'_coefs'[`row0'+`counter_rd',2]
634
+ }
635
+ else if (`"`linetype'"'=="qfit") {
636
+ local coef_quad=`y`counter_depvar'_coefs'[`row0'+`counter_rd',1]
637
+ local coef_lin=`y`counter_depvar'_coefs'[`row0'+`counter_rd',2]
638
+ local coef_cons=`y`counter_depvar'_coefs'[`row0'+`counter_rd',3]
639
+ }
640
+
641
+ if !missing(`coef_quad',`coef_lin',`coef_cons') {
642
+ local leftbound=`fitline_bounds'[1,`counter_rd']
643
+ local rightbound=`fitline_bounds'[1,`counter_rd'+1]
644
+
645
+ local fits `fits' (function `coef_quad'*x^2+`coef_lin'*x+`coef_cons', range(`leftbound' `rightbound') lcolor(`: word `c' of `lcolors''))
646
+ }
647
+ }
648
+ }
649
+ }
650
+ }
651
+
652
+ * Prepare y-axis title
653
+ if (`ynum'==1) local ytitle `y_vars'
654
+ else if (`ynum'==2) local ytitle : subinstr local y_vars " " " and "
655
+ else local ytitle : subinstr local y_vars " " "; ", all
656
+
657
+ * Display graph
658
+ local graphcmd twoway `scatters' `fits', graphregion(fcolor(white)) `xlines' xtitle(`x_var') ytitle(`ytitle') legend(`legend_labels' order(`order')) `options'
659
+ if ("`savedata'"!="") local savedata_graphcmd twoway `savedata_scatters' `fits', graphregion(fcolor(white)) `xlines' xtitle(`x_var') ytitle(`ytitle') legend(`legend_labels' order(`order')) `options'
660
+ `graphcmd'
661
+
662
+ ****** Save results ******
663
+
664
+ * Save graph
665
+ if `"`savegraph'"'!="" {
666
+ * check file extension using a regular expression
667
+ if regexm(`"`savegraph'"',"\.[a-zA-Z0-9]+$") local graphextension=regexs(0)
668
+
669
+ if inlist(`"`graphextension'"',".gph","") graph save `"`savegraph'"', `replace'
670
+ else graph export `"`savegraph'"', `replace'
671
+ }
672
+
673
+ * Save data
674
+ if ("`savedata'"!="") {
675
+
676
+ *** Save a CSV containing the scatter points
677
+ tempname savedatafile
678
+ file open `savedatafile' using `"`savedata'.csv"', write text `replace'
679
+
680
+ * LOOP over rows
681
+ forvalues row=0/`nquantiles' {
682
+
683
+ *** Put the x-variable at the left
684
+ * LOOP over by-vals
685
+ forvalues counter_by=1/`bynum' {
686
+
687
+ if (`row'==0) { /* write variable names */
688
+ if "`by'"!="" local bynlabel _by`counter_by'
689
+ file write `savedatafile' "`x_var'`bynlabel',"
690
+ }
691
+ else { /* write data values */
692
+ if (`row'<=`=rowsof(`y1_scatterpts')') file write `savedatafile' (`y1_scatterpts'[`row',`counter_by'*2-1]) ","
693
+ else file write `savedatafile' ".,"
694
+ }
695
+ }
696
+
697
+ *** Now y-variables at the right
698
+
699
+ * LOOP over y-vars
700
+ local counter_depvar=0
701
+ foreach depvar of varlist `y_vars' {
702
+ local ++counter_depvar
703
+
704
+ * LOOP over by-vals
705
+ forvalues counter_by=1/`bynum' {
706
+
707
+
708
+ if (`row'==0) { /* write variable names */
709
+ if "`by'"!="" local bynlabel _by`counter_by'
710
+ file write `savedatafile' "`depvar'`bynlabel'"
711
+ }
712
+ else { /* write data values */
713
+ if (`row'<=`=rowsof(`y`counter_depvar'_scatterpts')') file write `savedatafile' (`y`counter_depvar'_scatterpts'[`row',`counter_by'*2])
714
+ else file write `savedatafile' "."
715
+ }
716
+
717
+ * unless this is the last variable in the dataset, add a comma
718
+ if !(`counter_depvar'==`ynum' & `counter_by'==`bynum') file write `savedatafile' ","
719
+
720
+ } /* end by-val loop */
721
+
722
+ } /* end y-var loop */
723
+
724
+ file write `savedatafile' _n
725
+
726
+ } /* end row loop */
727
+
728
+ file close `savedatafile'
729
+ di as text `"(file `savedata'.csv written containing saved data)"'
730
+
731
+
732
+
733
+ *** Save a do-file with the commands to generate a nicely labeled dataset and re-create the binscatter graph
734
+
735
+ file open `savedatafile' using `"`savedata'.do"', write text `replace'
736
+
737
+ file write `savedatafile' `"insheet using `savedata'.csv"' _n _n
738
+
739
+ if "`by'"!="" {
740
+ foreach var of varlist `x_var' `y_vars' {
741
+ local counter_by=0
742
+ foreach byval in `byvals' {
743
+ local ++counter_by
744
+ if ("`bylabel'"=="") local byvalname=`byval'
745
+ else {
746
+ local byvalname `: label `bylabel' `byval''
747
+ }
748
+ file write `savedatafile' `"label variable `var'_by`counter_by' "`var'; `byvarname'==`byvalname'""' _n
749
+ }
750
+ }
751
+ file write `savedatafile' _n
752
+ }
753
+
754
+ file write `savedatafile' `"`savedata_graphcmd'"' _n
755
+
756
+ file close `savedatafile'
757
+ di as text `"(file `savedata'.do written containing commands to process saved data)"'
758
+
759
+ }
760
+
761
+ *** Return items
762
+ ereturn post, esample(`touse')
763
+
764
+ ereturn scalar N = `samplesize'
765
+
766
+ ereturn local graphcmd `"`graphcmd'"'
767
+ if inlist("`linetype'","lfit","qfit") {
768
+ forvalues yi=`ynum'(-1)1 {
769
+ ereturn matrix y`yi'_coefs=`y`yi'_coefs'
770
+ }
771
+ }
772
+
773
+ if ("`rd'"!="") {
774
+ tempname rdintervals
775
+ matrix `rdintervals' = (. \ `=subinstr("`rd'"," ","\",.)' ) , ( `=subinstr("`rd'"," ","\",.)' \ .)
776
+
777
+ forvalues i=1/`=rowsof(`rdintervals')' {
778
+ local rdintervals_labels `rdintervals_labels' rd`i'
779
+ }
780
+ matrix rownames `rdintervals' = `rdintervals_labels'
781
+ matrix colnames `rdintervals' = gt lt_eq
782
+ ereturn matrix rdintervals=`rdintervals'
783
+ }
784
+
785
+ if ("`by'"!="" & "`by'"=="`byvarname'") { /* if a numeric by-variable was specified */
786
+ forvalues i=1/`=rowsof(`byvalmatrix')' {
787
+ local byvalmatrix_labels `byvalmatrix_labels' by`i'
788
+ }
789
+ matrix rownames `byvalmatrix' = `byvalmatrix_labels'
790
+ matrix colnames `byvalmatrix' = `by'
791
+ ereturn matrix byvalues=`byvalmatrix'
792
+ }
793
+
794
+ end
795
+
796
+
797
+ **********************************
798
+
799
+ * Helper programs
800
+
801
+ program define means_in_boundaries, rclass
802
+ version 12.1
803
+
804
+ syntax varname(numeric) [aweight fweight], BOUNDsmat(name) [MEDians]
805
+
806
+ * Create convenient weight local
807
+ if ("`weight'"!="") local wt [`weight'`exp']
808
+
809
+ local r=rowsof(`boundsmat')
810
+ matrix means=J(`r',1,.)
811
+
812
+ if ("`medians'"!="medians") {
813
+ forvalues i=1/`r' {
814
+ sum `varlist' in `=`boundsmat'[`i',1]'/`=`boundsmat'[`i',2]' `wt', meanonly
815
+ matrix means[`i',1]=r(mean)
816
+ }
817
+ }
818
+ else {
819
+ forvalues i=1/`r' {
820
+ _pctile `varlist' in `=`boundsmat'[`i',1]'/`=`boundsmat'[`i',2]' `wt', percentiles(50)
821
+ matrix means[`i',1]=r(r1)
822
+ }
823
+ }
824
+
825
+ return clear
826
+ return matrix means=means
827
+
828
+ end
829
+
830
+ *** copy of: version 1.21 8oct2013 Michael Stepner, [email protected]
831
+ program define fastxtile, rclass
832
+ version 11
833
+
834
+ * Parse weights, if any
835
+ _parsewt "aweight fweight pweight" `0'
836
+ local 0 "`s(newcmd)'" /* command minus weight statement */
837
+ local wt "`s(weight)'" /* contains [weight=exp] or nothing */
838
+
839
+ * Extract parameters
840
+ syntax newvarname=/exp [if] [in] [,Nquantiles(integer 2) Cutpoints(varname numeric) ALTdef ///
841
+ CUTValues(numlist ascending) randvar(varname numeric) randcut(real 1) randn(integer -1)]
842
+
843
+ * Mark observations which will be placed in quantiles
844
+ marksample touse, novarlist
845
+ markout `touse' `exp'
846
+ qui count if `touse'
847
+ local popsize=r(N)
848
+
849
+ if "`cutpoints'"=="" & "`cutvalues'"=="" { /***** NQUANTILES *****/
850
+ if `"`wt'"'!="" & "`altdef'"!="" {
851
+ di as error "altdef option cannot be used with weights"
852
+ exit 198
853
+ }
854
+
855
+ if `randn'!=-1 {
856
+ if `randcut'!=1 {
857
+ di as error "cannot specify both randcut() and randn()"
858
+ exit 198
859
+ }
860
+ else if `randn'<1 {
861
+ di as error "randn() must be a positive integer"
862
+ exit 198
863
+ }
864
+ else if `randn'>`popsize' {
865
+ di as text "randn() is larger than the population. using the full population."
866
+ local randvar=""
867
+ }
868
+ else {
869
+ local randcut=`randn'/`popsize'
870
+
871
+ if "`randvar'"!="" {
872
+ qui sum `randvar', meanonly
873
+ if r(min)<0 | r(max)>1 {
874
+ di as error "with randn(), the randvar specified must be in [0,1] and ought to be uniformly distributed"
875
+ exit 198
876
+ }
877
+ }
878
+ }
879
+ }
880
+
881
+ * Check if need to gen a temporary uniform random var
882
+ if "`randvar'"=="" {
883
+ if (`randcut'<1 & `randcut'>0) {
884
+ tempvar randvar
885
+ gen `randvar'=runiform()
886
+ }
887
+ * randcut sanity check
888
+ else if `randcut'!=1 {
889
+ di as error "if randcut() is specified without randvar(), a uniform r.v. will be generated and randcut() must be in (0,1)"
890
+ exit 198
891
+ }
892
+ }
893
+
894
+ * Mark observations used to calculate quantile boundaries
895
+ if ("`randvar'"!="") {
896
+ tempvar randsample
897
+ mark `randsample' `wt' if `touse' & `randvar'<=`randcut'
898
+ }
899
+ else {
900
+ local randsample `touse'
901
+ }
902
+
903
+ * Error checks
904
+ qui count if `randsample'
905
+ local samplesize=r(N)
906
+ if (`nquantiles' > r(N) + 1) {
907
+ if ("`randvar'"=="") di as error "nquantiles() must be less than or equal to the number of observations [`r(N)'] plus one"
908
+ else di as error "nquantiles() must be less than or equal to the number of sampled observations [`r(N)'] plus one"
909
+ exit 198
910
+ }
911
+ else if (`nquantiles' < 2) {
912
+ di as error "nquantiles() must be greater than or equal to 2"
913
+ exit 198
914
+ }
915
+
916
+ * Compute quantile boundaries
917
+ _pctile `exp' if `randsample' `wt', nq(`nquantiles') `altdef'
918
+
919
+ * Store quantile boundaries in list
920
+ forvalues i=1/`=`nquantiles'-1' {
921
+ local cutvallist `cutvallist' r(r`i')
922
+ }
923
+ }
924
+ else if "`cutpoints'"!="" { /***** CUTPOINTS *****/
925
+
926
+ * Parameter checks
927
+ if "`cutvalues'"!="" {
928
+ di as error "cannot specify both cutpoints() and cutvalues()"
929
+ exit 198
930
+ }
931
+ if "`wt'"!="" | "`randvar'"!="" | "`ALTdef'"!="" | `randcut'!=1 | `nquantiles'!=2 | `randn'!=-1 {
932
+ di as error "cutpoints() cannot be used with nquantiles(), altdef, randvar(), randcut(), randn() or weights"
933
+ exit 198
934
+ }
935
+
936
+ tempname cutvals
937
+ qui tab `cutpoints', matrow(`cutvals')
938
+
939
+ if r(r)==0 {
940
+ di as error "cutpoints() all missing"
941
+ exit 2000
942
+ }
943
+ else {
944
+ local nquantiles = r(r) + 1
945
+
946
+ forvalues i=1/`r(r)' {
947
+ local cutvallist `cutvallist' `cutvals'[`i',1]
948
+ }
949
+ }
950
+ }
951
+ else { /***** CUTVALUES *****/
952
+ if "`wt'"!="" | "`randvar'"!="" | "`ALTdef'"!="" | `randcut'!=1 | `nquantiles'!=2 | `randn'!=-1 {
953
+ di as error "cutvalues() cannot be used with nquantiles(), altdef, randvar(), randcut(), randn() or weights"
954
+ exit 198
955
+ }
956
+
957
+ * parse numlist
958
+ numlist "`cutvalues'"
959
+ local cutvallist `"`r(numlist)'"'
960
+ local nquantiles=wordcount(`"`r(numlist)'"')+1
961
+ }
962
+
963
+ * Pick data type for quantile variable
964
+ if (`nquantiles'<=100) local qtype byte
965
+ else if (`nquantiles'<=32,740) local qtype int
966
+ else local qtype long
967
+
968
+ * Create quantile variable
969
+ local cutvalcommalist : subinstr local cutvallist " " ",", all
970
+ qui gen `qtype' `varlist'=1+irecode(`exp',`cutvalcommalist') if `touse'
971
+ label var `varlist' "`nquantiles' quantiles of `exp'"
972
+
973
+ * Return values
974
+ if ("`samplesize'"!="") return scalar n = `samplesize'
975
+ else return scalar n = .
976
+
977
+ return scalar N = `popsize'
978
+
979
+ tokenize `"`cutvallist'"'
980
+ forvalues i=`=`nquantiles'-1'(-1)1 {
981
+ return scalar r`i' = ``i''
982
+ }
983
+
984
+ end
985
+
986
+
987
+ version 12.1
988
+ set matastrict on
989
+
990
+ mata:
991
+
992
+ void characterize_unique_vals_sorted(string scalar var, real scalar first, real scalar last, real scalar maxuq) {
993
+ // Inputs: a numeric variable, a starting & ending obs #, and a maximum number of unique values
994
+ // Requires: the data to be sorted on the specified variable within the observation boundaries given
995
+ // (no check is made that this requirement is satisfied)
996
+ // Returns: the number of unique values found
997
+ // the unique values found
998
+ // the observation boundaries of each unique value in the dataset
999
+
1000
+
1001
+ // initialize returned results
1002
+ real scalar Nunique
1003
+ Nunique=0
1004
+
1005
+ real matrix values
1006
+ values=J(maxuq,1,.)
1007
+
1008
+ real matrix boundaries
1009
+ boundaries=J(maxuq,2,.)
1010
+
1011
+ // initialize computations
1012
+ real scalar var_index
1013
+ var_index=st_varindex(var)
1014
+
1015
+ real scalar curvalue
1016
+ real scalar prevvalue
1017
+
1018
+ // perform computations
1019
+ real scalar obs
1020
+ for (obs=first; obs<=last; obs++) {
1021
+ curvalue=_st_data(obs,var_index)
1022
+
1023
+ if (curvalue!=prevvalue) {
1024
+ Nunique++
1025
+ if (Nunique<=maxuq) {
1026
+ prevvalue=curvalue
1027
+ values[Nunique,1]=curvalue
1028
+ boundaries[Nunique,1]=obs
1029
+ if (Nunique>1) boundaries[Nunique-1,2]=obs-1
1030
+ }
1031
+ else {
1032
+ exit(error(134))
1033
+ }
1034
+
1035
+ }
1036
+ }
1037
+ boundaries[Nunique,2]=last
1038
+
1039
+ // return results
1040
+ stata("return clear")
1041
+
1042
+ st_numscalar("r(r)",Nunique)
1043
+ st_matrix("r(values)",values[1..Nunique,.])
1044
+ st_matrix("r(boundaries)",boundaries[1..Nunique,.])
1045
+
1046
+ }
1047
+
1048
+ end
110/replication_package/replication/ado/plus/b/binscatter.sthlp ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {smcl}
2
+ {* *! version 7.02 24nov2013}{...}
3
+ {viewerjumpto "Syntax" "binscatter##syntax"}{...}
4
+ {viewerjumpto "Description" "binscatter##description"}{...}
5
+ {viewerjumpto "Options" "binscatter##options"}{...}
6
+ {viewerjumpto "Examples" "binscatter##examples"}{...}
7
+ {viewerjumpto "Saved results" "binscatter##saved_results"}{...}
8
+ {viewerjumpto "Author" "binscatter##author"}{...}
9
+ {viewerjumpto "Acknowledgements" "binscatter##acknowledgements"}{...}
10
+ {title:Title}
11
+
12
+ {p2colset 5 19 21 2}{...}
13
+ {p2col :{hi:binscatter} {hline 2}}Binned scatterplots{p_end}
14
+ {p2colreset}{...}
15
+
16
+
17
+ {marker syntax}{title:Syntax}
18
+
19
+ {p 8 15 2}
20
+ {cmd:binscatter}
21
+ {varlist} {ifin}
22
+ {weight}
23
+ [{cmd:,} {it:options}]
24
+
25
+
26
+ {pstd}
27
+ where {it:varlist} is
28
+ {p_end}
29
+ {it:y_1} [{it:y_2} [...]] {it:x}
30
+
31
+ {synoptset 26 tabbed}{...}
32
+ {synopthdr :options}
33
+ {synoptline}
34
+ {syntab :Main}
35
+ {synopt :{opth by(varname)}}plot separate series for each group (see {help binscatter##by_notes:important notes below}){p_end}
36
+ {synopt :{opt med:ians}}plot within-bin medians instead of means{p_end}
37
+
38
+ {syntab :Bins}
39
+ {synopt :{opth n:quantiles(#)}}number of equal-sized bins to be created; default is {bf:20}{p_end}
40
+ {synopt :{opth gen:xq(varname)}}generate quantile variable containing the bins{p_end}
41
+ {synopt :{opt discrete}}each x-value to be used as a separate bin{p_end}
42
+ {synopt :{opth xq(varname)}}variable which already contains bins; bins therefore not recomputed{p_end}
43
+
44
+ {syntab :Controls}
45
+ {synopt :{opth control:s(varlist)}}residualize the x & y variables on controls before plotting{p_end}
46
+ {synopt :{opth absorb(varname)}}residualize the x & y variables on a categorical variable{p_end}
47
+ {synopt :{opt noa:ddmean}}do not add the mean of each variable back to its residuals{p_end}
48
+
49
+ {syntab :Fit Line}
50
+ {synopt :{opth line:type(binscatter##linetype:linetype)}}type of fit line; default is {bf:lfit}, may also be {bf:qfit}, {bf:connect}, or {bf:none}{p_end}
51
+ {synopt :{opth rd(numlist)}}create regression discontinuity at x-values{p_end}
52
+ {synopt :{opt reportreg}}display the regressions used to estimate the fit lines{p_end}
53
+
54
+ {syntab :Graph Style}
55
+ {synopt :{cmdab:col:ors(}{it:{help colorstyle}list}{cmd:)}}ordered list of colors{p_end}
56
+ {synopt :{cmdab:mc:olors(}{it:{help colorstyle}list}{cmd:)}}overriding ordered list of colors for the markers{p_end}
57
+ {synopt :{cmdab:lc:olors(}{it:{help colorstyle}list}{cmd:)}}overriding ordered list of colors for the lines{p_end}
58
+ {synopt :{cmdab:m:symbols(}{it:{help symbolstyle}list}{cmd:)}}ordered list of symbols{p_end}
59
+ {synopt :{it:{help twoway_options}}}{help title options:titles}, {help legend option:legends}, {help axis options:axes}, added {help added line options:lines} and {help added text options:text},
60
+ {help region options:regions}, {help name option:name}, {help aspect option:aspect ratio}, etc.{p_end}
61
+
62
+ {syntab :Save Output}
63
+ {synopt :{opt savegraph(filename)}}save graph to file; format automatically detected from extension [ex: .gph .jpg .png]{p_end}
64
+ {synopt :{opt savedata(filename)}}save {it:filename}.csv containg scatterpoint data, and {it:filename}.do to process data into graph{p_end}
65
+ {synopt :{opt replace}}overwrite existing files{p_end}
66
+
67
+ {syntab :fastxtile options}
68
+ {synopt :{opt nofastxtile}}use xtile instead of fastxtile{p_end}
69
+ {synopt :{opth randvar(varname)}}use {it:varname} to sample observations when computing quantile boundaries{p_end}
70
+ {synopt :{opt randcut(#)}}upper bound on {cmd:randvar()} used to cut the sample; default is {cmd:randcut(1)}{p_end}
71
+ {synopt :{opt randn(#)}}number of observations to sample when computing quantile boundaries{p_end}
72
+ {synoptline}
73
+ {p 4 6 2}
74
+ {opt aweight}s and {opt fweight}s are allowed;
75
+ see {help weight}.
76
+ {p_end}
77
+
78
+
79
+ {marker description}{...}
80
+ {title:Description}
81
+
82
+ {pstd}
83
+ {opt binscatter} generates binned scatterplots, and is optimized for speed in large datasets.
84
+
85
+ {pstd}
86
+ Binned scatterplots provide a non-parametric way of visualizing the relationship between two variables.
87
+ With a large number of observations, a scatterplot that plots every data point would become too crowded
88
+ to interpret visually. {cmd:binscatter} groups the x-axis variable into equal-sized bins, computes the
89
+ mean of the x-axis and y-axis variables within each bin, then creates a scatterplot of these data points.
90
+ The result is a non-parametric visualization of the conditional expectation function.
91
+
92
+ {pstd}
93
+ {opt binscatter} provides built-in options to control for covariates before plotting the relationship
94
+ (see {help binscatter##controls:Controls}). Additionally, {cmd:binscatter} will plot fit lines based
95
+ on the underlying data, and can automatically handle regression discontinuities (see {help binscatter##fit_line:Fit Line}).
96
+
97
+
98
+ {marker options}{...}
99
+ {title:Options}
100
+
101
+ {dlgtab:Main}
102
+
103
+ {marker by_notes}{...}
104
+ {phang}{opth by(varname)} plots a separate series for each by-value. Both numeric and string by-variables
105
+ are supported, but numeric by-variables will have faster run times.
106
+
107
+ {pmore}Users should be aware of the two ways in which {cmd:binscatter} does not condition on by-values:
108
+
109
+ {phang3}1) When combined with {opt controls()} or {opt absorb()}, the program residualizes using the restricted model in which each covariate
110
+ has the same coefficient in each by-value sample. It does not run separate regressions for each by-value. If you wish to control for
111
+ covariates using a different model, you can residualize your x- and y-variables beforehand using your desired model then run {cmd:binscatter}
112
+ on the residuals you constructed.
113
+
114
+ {phang3}2) When not combined with {opt discrete} or {opt xq()}, the program constructs a single set of bins
115
+ using the unconditional quantiles of the x-variable. It does not bin the x-variable separately for each by-value.
116
+ If you wish to use a different binning procedure (such as constructing equal-sized bins separately for each
117
+ by-value), you can construct a variable containing your desired bins beforehand, then run {cmd:binscatter} with {opt xq()}.
118
+
119
+ {phang}{opt med:ians} creates the binned scatterplot using the median x- and y-value within each bin, rather than the mean.
120
+ This option only affects the scatter points; it does not, for instance, cause {opt linetype(lfit)}
121
+ to use quantile regression instead of OLS when drawing a fit line.
122
+
123
+ {dlgtab:Bins}
124
+
125
+ {phang}{opth n:quantiles(#)} specifies the number of equal-sized bins to be created. This is equivalent to the number of
126
+ points in each series. The default is {bf:20}. If the x-variable has fewer
127
+ unique values than the number of bins specified, then {opt discrete} will be automatically invoked, and no
128
+ binning will be performed.
129
+ This option cannot be combined with {opt discrete} or {opt xq()}.
130
+
131
+ {pmore}
132
+ Binning is performed after residualization when combined with {opt controls()} or {opt absorb()}.
133
+ Note that the binning procedure is equivalent to running xtile, which in certain cases will generate
134
+ fewer quantile categories than specified. (e.g. {stata sysuse auto}; {stata xtile temp=mpg, nq(20)}; {stata tab temp})
135
+
136
+ {phang}{opth gen:xq(varname)} creates a categorical variable containing the computed bins.
137
+ This option cannot be combined with {opt discrete} or {opt xq()}.
138
+
139
+ {phang}{opt discrete} specifies that the x-variable is discrete and that each x-value is to be treated as
140
+ a separate bin. {cmd:binscatter} will therefore plot the mean y-value associated with each x-value.
141
+ This option cannot be combined with {opt nquantiles()}, {opt genxq()} or {opt xq()}.
142
+
143
+ {pmore}
144
+ In most cases, {opt discrete} should not be combined with {opt controls()} or {opt absorb()}, since residualization occurs before binning,
145
+ and in general the residual of a discrete variable will not be discrete.
146
+
147
+ {phang}{opth xq(varname)} specifies a categorical variable that contains the bins to be used, instead of {cmd:binscatter} generating them.
148
+ This option is typically used to avoid recomputing the bins needlessly when {cmd:binscatter} is being run repeatedly on the same sample
149
+ and with the same x-variable.
150
+ It may be convenient to use {opt genxq(binvar)} in the first iteration, and specify {opt xq(binvar)} in subsequent iterations.
151
+ Computing quantiles is computationally intensive in large datasets, so avoiding repetition can reduce run times considerably.
152
+ This option cannot be combined with {opt nquantiles()}, {opt genxq()} or {opt discrete}.
153
+
154
+ {pmore}
155
+ Care should be taken when combining {opt xq()} with {opt controls()} or {opt absorb()}. Binning takes place after residualization,
156
+ so if the sample changes or the control variables change, the bins ought to be recomputed as well.
157
+
158
+ {marker controls}{...}
159
+ {dlgtab:Controls}
160
+
161
+ {phang}{opth control:s(varlist)} residualizes the x-variable and y-variables on the specified controls before binning and plotting.
162
+ To do so, {cmd:binscatter} runs a regression of each variable on the controls, generates the residuals, and adds the sample mean of
163
+ each variable back to its residuals.
164
+
165
+ {phang}{opth absorb(varname)} absorbs fixed effects in the categorical variable from the x-variable and y-variables before binning and plotting,
166
+ To do so, {cmd:binscatter} runs an {helpb areg} of each variable with {it:absorb(varname)} and any {opt controls()} specified. It then generates the
167
+ residuals and adds the sample mean of each variable back to its residuals.
168
+
169
+ {phang}{opt noa:ddmean} prevents the sample mean of each variable from being added back to its residuals, when combined with {opt controls()} or {opt absorb()}.
170
+
171
+ {marker fit_line}{...}
172
+ {dlgtab:Fit Line}
173
+
174
+ {marker linetype}{...}
175
+ {phang}{opth line:type(binscatter##linetype:linetype)} specifies the type of line plotted on each series.
176
+ The default is {bf:lfit}, which plots a linear fit line. Other options are {bf:qfit} for a quadratic fit line,
177
+ {bf:connect} for connected points, and {bf:none} for no line.
178
+
179
+ {pmore}Linear or quadratic fit lines are estimated using the underlying data, not the binned scatter points. When combined with
180
+ {opt controls()} or {opt absorb()}, the fit line is estimated after the variables have been residualized.
181
+
182
+ {phang}{opth rd(numlist)} draws a dashed vertical line at the specified x-values and generates regression discontinuities when combined with {opt line(lfit|qfit)}.
183
+ Separate fit lines will be estimated below and above each discontinuity. These estimations are performed using the underlying data, not the binned scatter points.
184
+
185
+ {pmore}The regression discontinuities do not affect the binned scatter points in any way.
186
+ Specifically, a bin may contain a discontinuity within its range, and therefore include data from both sides of the discontinuity.
187
+
188
+ {phang}{opt reportreg} displays the regressions used to estimate the fit lines in the results window.
189
+
190
+ {dlgtab:Graph Style}
191
+
192
+ {phang}{cmdab:col:ors(}{it:{help colorstyle}list}{cmd:)} specifies an ordered list of colors for each series
193
+
194
+ {phang}{cmdab:mc:olors(}{it:{help colorstyle}list}{cmd:)} specifies an ordered list of colors for the markers of each series, which overrides any list provided in {opt colors()}
195
+
196
+ {phang}{cmdab:lc:olors(}{it:{help colorstyle}list}{cmd:)} specifies an ordered list of colors for the line of each series, which overrides any list provided in {opt colors()}
197
+
198
+ {phang}{cmdab:m:symbols(}{it:{help symbolstyle}list}{cmd:)} specifies an ordered list of symbols for each series
199
+
200
+ {phang}{it:{help twoway_options}}:
201
+
202
+ {pmore}Any unrecognized options added to {cmd:binscatter} are appended to the end of the twoway command which generates the
203
+ binned scatter plot.
204
+
205
+ {pmore}These can be used to control the graph {help title options:titles},
206
+ {help legend option:legends}, {help axis options:axes}, added {help added line options:lines} and {help added text options:text},
207
+ {help region options:regions}, {help name option:name}, {help aspect option:aspect ratio}, etc.
208
+
209
+ {dlgtab:Save Output}
210
+
211
+ {phang}{opt savegraph(filename)} saves the graph to a file. The format is automatically detected from the extension specified [ex: {bf:.gph .jpg .png}],
212
+ and either {cmd:graph save} or {cmd:graph export} is run. If no file extension is specified {bf:.gph} is assumed.
213
+
214
+ {phang}{opt savedata(filename)} saves {it:filename}{bf:.csv} containing the binned scatterpoint data, and {it:filename}{bf:.do} which
215
+ loads the scatterpoint data, labels the variables, and plots the binscatter graph.
216
+
217
+ {pmore}Note that the saved result {bf:e(cmd)} provides an alternative way of capturing the binscatter graph and editing it.
218
+
219
+ {phang}{opt replace} specifies that files be overwritten if they alredy exist
220
+
221
+ {dlgtab:fastxtile options}
222
+
223
+ {phang}{opt nofastxtile} forces the use of {cmd:xtile} instead of {cmd:fastxtile} to compute bins. There is no situation where this should
224
+ be necessary or useful. The {cmd:fastxile} program generates identical results to {cmd:xtile}, but runs faster on large datasets, and has
225
+ additional options for random sampling which may be useful to increase speed.
226
+
227
+ {pmore}{cmd:fastxtile} is built into the {cmd:binscatter} code, but may also be installed
228
+ separately from SSC ({stata ssc install fastxtile:click here to install}) for use outside of {cmd:binscatter}.
229
+
230
+ {phang}{opth randvar(varname)} requests that {it:varname} be used to select a
231
+ sample of observations when computing the quantile boundaries. Sampling increases
232
+ the speed of the binning procedure, but generates bins which are only approximately equal-sized
233
+ due to sampling error. It is possible to omit this option and still perform random sampling from U[0,1]
234
+ as described below in {opt randcut()} and {opt randn()}.
235
+
236
+ {phang}{opt randcut(#)} specifies the upper bound on the variable contained
237
+ in {opt randvar(varname)}. Quantile boundaries are approximated using observations for which
238
+ {opt randvar()} <= #. If no variable is specified in {opt randvar()},
239
+ a standard uniform random variable is generated. The default is {cmd:randcut(1)}.
240
+ This option cannot be combined with {opt randn()}.
241
+
242
+ {phang}{opt randn(#)} specifies an approximate number of observations to sample when
243
+ computing the quantile boundaries. Quantile boundaries are approximated using observations
244
+ for which a uniform random variable is <= #/N. The exact number of observations
245
+ sampled may therefore differ from #, but it equals # in expectation. When this option is
246
+ combined with {opth randvar(varname)}, {it:varname} ought to be distributed U[0,1].
247
+ Otherwise, a standard uniform random variable is generated. This option cannot be combined
248
+ with {opt randcut()}.
249
+
250
+
251
+ {marker examples}{...}
252
+ {title:Examples}
253
+
254
+ {pstd}Load the 1988 extract of the National Longitudinal Survey of Young Women and Mature Women.{p_end}
255
+ {phang2}. {stata sysuse nlsw88}{p_end}
256
+ {phang2}. {stata keep if inrange(age,35,44) & inrange(race,1,2)}{p_end}
257
+
258
+ {pstd}What is the relationship between job tenure and wages?{p_end}
259
+ {phang2}. {stata scatter wage tenure}{p_end}
260
+ {phang2}. {stata binscatter wage tenure}{p_end}
261
+
262
+ {pstd}The scatter was too crowded to be easily interpetable. The binscatter is cleaner, but a linear fit looks unreasonable.{p_end}
263
+
264
+ {pstd}Try a quadratic fit.{p_end}
265
+ {phang2}. {stata binscatter wage tenure, line(qfit)}{p_end}
266
+
267
+ {pstd}We can also plot a linear regression discontinuity.{p_end}
268
+ {phang2}. {stata binscatter wage tenure, rd(2.5)}{p_end}
269
+
270
+ {pstd} What is the relationship between age and wages?{p_end}
271
+ {phang2}. {stata scatter wage age}{p_end}
272
+ {phang2}. {stata binscatter wage age}{p_end}
273
+
274
+ {pstd} The binscatter is again much easier to interpret. (Note that {cmd:binscatter} automatically
275
+ used each age as a discrete bin, since there are fewer than 20 unique values.){p_end}
276
+
277
+ {pstd}How does the relationship vary by race?{p_end}
278
+ {phang2}. {stata binscatter wage age, by(race)}{p_end}
279
+
280
+ {pstd} The relationship between age and wages is very different for whites and blacks. But what if we control for occupation?{p_end}
281
+ {phang2}. {stata binscatter wage age, by(race) absorb(occupation)}{p_end}
282
+
283
+ {pstd} A very different picture emerges. Let's label this graph nicely.{p_end}
284
+ {phang2}. {stata binscatter wage age, by(race) absorb(occupation) msymbols(O T) xtitle(Age) ytitle(Hourly Wage) legend(lab(1 White) lab(2 Black))}{p_end}
285
+
286
+
287
+ {marker saved_results}{...}
288
+ {title:Saved Results}
289
+
290
+ {pstd}
291
+ {cmd:binscatter} saves the following in {cmd:e()}:
292
+
293
+ {synoptset 20 tabbed}{...}
294
+ {p2col 5 20 24 2: Scalars}{p_end}
295
+ {synopt:{cmd:e(N)}}number of observations{p_end}
296
+
297
+ {synoptset 20 tabbed}{...}
298
+ {p2col 5 20 24 2: Macros}{p_end}
299
+ {synopt:{cmd:e(graphcmd)}}twoway command used to generate graph, which does not depend on loaded data{p_end}
300
+ {p 30 30 2}Note: it is often important to reference this result using `"`{bf:e(graphcmd)}'"'
301
+ rather than {bf:e(graphcmd)} in order to avoid truncation due to Stata's character limit for strings.
302
+
303
+ {synoptset 20 tabbed}{...}
304
+ {p2col 5 20 24 2: Matrices}{p_end}
305
+ {synopt:{cmd:e(byvalues)}}ordered list of by-values {it:(if numeric by-variable specified)}{p_end}
306
+ {synopt:{cmd:e(rdintervals)}}ordered list of rd intervals {it:(if rd specified)}{p_end}
307
+ {synopt:{cmd:e(y#_coefs)}}fit line coefficients for #th y-variable {it:(if lfit or qfit specified)}{p_end}
308
+
309
+ {synoptset 20 tabbed}{...}
310
+ {p2col 5 20 24 2: Functions}{p_end}
311
+ {synopt:{cmd:e(sample)}}marks sample{p_end}
312
+ {p2colreset}{...}
313
+
314
+
315
+ {marker author}{...}
316
+ {title:Author}
317
+
318
+ {pstd}Michael Stepner{p_end}
319
+ {pstd}[email protected]{p_end}
320
+
321
+
322
+ {marker acknowledgements}{...}
323
+ {title:Acknowledgements}
324
+
325
+ {pstd}The present version of {cmd:binscatter} is based on a program first written by Jessica Laird.
326
+
327
+ {pstd}This program was developed under the guidance and direction of Raj Chetty and John
328
+ Friedman. Laszlo Sandor provided suggestions which improved the program considerably, and offered abundant help
329
+ testing it.
330
+
331
+ {pstd}Thank you also to the users of early versions of the program who devoted time to reporting
332
+ the bugs that they encountered.
110/replication_package/replication/ado/plus/b/binslogit.ado ADDED
@@ -0,0 +1,2394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *! version 1.2 09-Oct-2022
2
+
3
+ capture program drop binslogit
4
+ program define binslogit, eclass
5
+ version 13
6
+
7
+ syntax varlist(min=2 numeric fv ts) [if] [in] [fw pw] [, deriv(integer 0) at(string asis) nolink ///
8
+ logitopt(string asis) ///
9
+ dots(string) dotsgrid(string) dotsplotopt(string asis) ///
10
+ line(string) linegrid(integer 20) lineplotopt(string asis) ///
11
+ ci(string) cigrid(string) ciplotopt(string asis) ///
12
+ cb(string) cbgrid(integer 20) cbplotopt(string asis) ///
13
+ polyreg(string) polyreggrid(integer 20) polyregcigrid(integer 0) polyregplotopt(string asis) ///
14
+ by(varname) bycolors(string asis) bysymbols(string asis) bylpatterns(string asis) ///
15
+ nbins(string) binspos(string) binsmethod(string) nbinsrot(string) ///
16
+ pselect(numlist integer >=0) sselect(numlist integer >=0) ///
17
+ samebinsby randcut(numlist max=1 >=0 <=1) ///
18
+ nsims(integer 500) simsgrid(integer 20) simsseed(numlist integer max=1 >=0) ///
19
+ dfcheck(numlist integer max=2 >=0) masspoints(string) usegtools(string) ///
20
+ vce(passthru) level(real 95) asyvar(string) ///
21
+ noplot savedata(string asis) replace ///
22
+ plotxrange(numlist asc max=2) plotyrange(numlist asc max=2) *]
23
+
24
+ *********************************************
25
+ * Regularization constant (for checking only)
26
+ local qrot=2
27
+
28
+ **************************************
29
+ * Create weight local
30
+ if ("`weight'"!="") {
31
+ local wt [`weight'`exp']
32
+ local wtype=substr("`weight'",1,1)
33
+ }
34
+
35
+ **********************
36
+ ** Extract options ***
37
+ **********************
38
+ * report the results for the cond. mean model?
39
+ if ("`link'"!="") local transform "F"
40
+ else local transform "T"
41
+
42
+ * default vce, clustered?
43
+ if ("`vce'"=="") local vce "vce(robust)"
44
+ local vcetemp: subinstr local vce "vce(" "", all
45
+ local vcetemp: subinstr local vcetemp ")" "", all
46
+ tokenize "`vcetemp'"
47
+ if ("`1'"=="cl"|"`1'"=="clu"|"`1'"=="clus"|"`1'"=="clust"| ///
48
+ "`1'"=="cluste"|"`1'"=="cluster") {
49
+ local clusterON "T" /* Mark cluster is specified */
50
+ local clustervar `2'
51
+ }
52
+ if ("`vce'"=="vce(oim)"|"`vce'"=="vce(opg)") local vce_select "vce(ols)"
53
+ else local vce_select "`vce'"
54
+
55
+ if ("`asyvar'"=="") local asyvar "off"
56
+ if ("`binsmethod'"=="rot") local binsmethod "ROT"
57
+ if ("`binsmethod'"=="dpi") local binsmethod "DPI"
58
+ if ("`binsmethod'"=="") local binsmethod "DPI"
59
+ if ("`binspos'"=="es") local binspos "ES"
60
+ if ("`binspos'"=="qs") local binspos "QS"
61
+ if ("`binspos'"=="") local binspos "QS"
62
+
63
+
64
+ * analyze options related to degrees *************
65
+ if ("`dots'"!="T"&"`dots'"!="F"&"`dots'"!="") {
66
+ numlist "`dots'", integer max(2) range(>=0)
67
+ local dots=r(numlist)
68
+ }
69
+ if ("`line'"!="T"&"`line'"!="F"&"`line'"!="") {
70
+ numlist "`line'", integer max(2) range(>=0)
71
+ local line=r(numlist)
72
+ }
73
+ if ("`ci'"!="T"&"`ci'"!="F"&"`ci'"!="") {
74
+ numlist "`ci'", integer max(2) range(>=0)
75
+ local ci=r(numlist)
76
+ }
77
+ if ("`cb'"!="T"&"`cb'"!="F"&"`cb'"!="") {
78
+ numlist "`cb'", integer max(2) range(>=0)
79
+ local cb=r(numlist)
80
+ }
81
+
82
+
83
+ if ("`dots'"=="F") { /* shut down dots */
84
+ local dots ""
85
+ local dotsgrid 0
86
+ }
87
+ if ("`line'"=="F") local line ""
88
+ if ("`ci'"=="F") local ci ""
89
+ if ("`cb'"=="F") local cb ""
90
+
91
+
92
+ ***************************************************************
93
+ * 4 cases: select J, select p, user specified both, and error
94
+ local selection ""
95
+
96
+ * analyze nbins
97
+ if ("`nbins'"=="T") local nbins=0
98
+ local len_nbins=0
99
+ if ("`nbins'"!=""&"`nbins'"!="F") {
100
+ numlist "`nbins'", integer sort
101
+ local nbins=r(numlist)
102
+ local len_nbins: word count `nbins'
103
+ }
104
+
105
+ * analyze numlist in pselect and sselect
106
+ local len_p=0
107
+ local len_s=0
108
+
109
+ if ("`pselect'"!="") {
110
+ numlist "`pselect'", integer range(>=`deriv') sort
111
+ local plist=r(numlist)
112
+ }
113
+
114
+ if ("`sselect'"!="") {
115
+ numlist "`sselect'", integer range(>=0) sort
116
+ local slist=r(numlist)
117
+ }
118
+
119
+ local len_p: word count `plist'
120
+ local len_s: word count `slist'
121
+
122
+ if (`len_p'==1&`len_s'==0) {
123
+ local slist `plist'
124
+ local len_s=1
125
+ }
126
+ if (`len_p'==0&`len_s'==1) {
127
+ local plist `slist'
128
+ local len_p=1
129
+ }
130
+
131
+ if ("`binspos'"!="ES"&"`binspos'"!="QS") {
132
+ if ("`nbins'"!=""|"`pselect'"!=""|"`sselect'"!="") {
133
+ di as error "nbins(), pselect() or sselect() incorrectly specified."
134
+ exit
135
+ }
136
+ }
137
+
138
+
139
+ * 1st case: select J
140
+ if (("`nbins'"=="0"|`len_nbins'>1|"`nbins'"=="")&("`binspos'"=="ES"|"`binspos'"=="QS")) local selection "J"
141
+ if ("`selection'"=="J") {
142
+ if (`len_p'>1|`len_s'>1) {
143
+ if ("`nbins'"=="") {
144
+ di as error "nbins() must be specified for degree/smoothness selection."
145
+ exit
146
+ }
147
+ else {
148
+ di as error "Only one p and one s are allowed to select # of bins."
149
+ exit
150
+ }
151
+ }
152
+ if ("`plist'"=="") local plist=`deriv'
153
+ if ("`slist'"=="") local slist=`plist'
154
+ if ("`dots'"!=""&"`dots'"!="T"&"`dots'"!="F") { /* respect user-specified dots */
155
+ local plist: word 1 of `dots'
156
+ local slist: word 2 of `dots'
157
+ if ("`slist'"=="") local slist `plist'
158
+ }
159
+ if ("`dots'"==""|"`dots'"=="T") local dots `plist' `slist' /* selection is based on dots */
160
+ if ("`line'"=="T") local line `plist' `slist'
161
+ if ("`ci'"=="T") local ci `=`plist'+1' `=`slist'+1'
162
+ if ("`cb'"=="T") local cb `=`plist'+1' `=`slist'+1'
163
+ local len_p=1
164
+ local len_s=1
165
+ } /* e.g., binsreg y x, nbins(a b) or nbins(T) or pselect(a) nbins(T) */
166
+
167
+
168
+ * 2nd case: select P (at least for one object)
169
+ if ("`selection'"!="J" & ("`dots'"==""|"`dots'"=="T"|"`line'"=="T"|"`ci'"=="T"|"`cb'"=="T")) {
170
+ local pselectOK "T" /* p selection CAN be turned on as long as one of the four is T */
171
+ }
172
+
173
+ if ("`pselectOK'"=="T" & `len_nbins'==1 & (`len_p'>1|`len_s'>1)) {
174
+ local selection "P"
175
+ } /* e.g., binsreg y x, pselect(a b) or pselect() dots(T) */
176
+
177
+ * 3rd case: completely user-specified J and p
178
+ if ((`len_p'<=1&`len_s'<=1) & "`selection'"!="J") {
179
+ local selection "NA"
180
+ if ("`dots'"==""|"`dots'"=="T") {
181
+ if (`len_p'==1&`len_s'==1) local dots `plist' `slist'
182
+ else local dots `deriv' `deriv' /* e.g., binsreg y x or , dots(0 0) nbins(20) */
183
+ }
184
+ tokenize `dots'
185
+ if ("`2'"=="") local 2 `1'
186
+ if ("`line'"=="T") {
187
+ if (`len_p'==1&`len_s'==1) local line `plist' `slist'
188
+ else local line `dots'
189
+ }
190
+ if ("`ci'"=="T") {
191
+ if (`len_p'==1&`len_s'==1) local ci `=`plist'+1' `=`slist'+1'
192
+ else local ci `=`1'+1' `=`2'+1'
193
+ }
194
+ if ("`cb'"=="T") {
195
+ if (`len_p'==1&`len_s'==1) local cb `=`plist'+1' `=`slist'+1'
196
+ else local cb `=`1'+1' `=`2'+1'
197
+ }
198
+ }
199
+
200
+ * exclude all other cases
201
+ if ("`selection'"=="") {
202
+ di as error "Degree, smoothness, or # of bins are not correctly specified."
203
+ exit
204
+ }
205
+
206
+
207
+ ****** Now, extract from dots, line, etc. ************
208
+ * dots
209
+ tokenize `dots'
210
+ local dots_p "`1'"
211
+ local dots_s "`2'"
212
+ if ("`dots_p'"==""|"`dots_p'"=="T") local dots_p=.
213
+ if ("`dots_s'"=="") local dots_s `dots_p'
214
+
215
+ if ("`dotsgrid'"=="") local dotsgrid "mean"
216
+ local dotsngrid_mean=0
217
+ if (strpos("`dotsgrid'","mean")!=0) {
218
+ local dotsngrid_mean=1
219
+ local dotsgrid: subinstr local dotsgrid "mean" "", all
220
+ }
221
+ if (wordcount("`dotsgrid'")==0) local dotsngrid=0
222
+ else {
223
+ confirm integer n `dotsgrid'
224
+ local dotsngrid `dotsgrid'
225
+ }
226
+ local dotsntot=`dotsngrid_mean'+`dotsngrid'
227
+
228
+
229
+ * line
230
+ tokenize `line'
231
+ local line_p "`1'"
232
+ local line_s "`2'"
233
+ local linengrid `linegrid'
234
+ if ("`line'"=="") local linengrid=0
235
+ if ("`line_p'"==""|"`line_p'"=="T") local line_p=.
236
+ if ("`line_s'"=="") local line_s `line_p'
237
+
238
+ * ci
239
+ if ("`cigrid'"=="") local cigrid "mean"
240
+ local cingrid_mean=0
241
+ if (strpos("`cigrid'","mean")!=0) {
242
+ local cingrid_mean=1
243
+ local cigrid: subinstr local cigrid "mean" "", all
244
+ }
245
+ if (wordcount("`cigrid'")==0) local cingrid=0
246
+ else {
247
+ confirm integer n `cigrid'
248
+ local cingrid `cigrid'
249
+ }
250
+ local cintot=`cingrid_mean'+`cingrid'
251
+
252
+ tokenize `ci'
253
+ local ci_p "`1'"
254
+ local ci_s "`2'"
255
+ if ("`ci'"=="") local cintot=0
256
+ if ("`ci_p'"==""|"`ci_p'"=="T") local ci_p=.
257
+ if ("`ci_s'"=="") local ci_s `ci_p'
258
+
259
+ * cb
260
+ tokenize `cb'
261
+ local cb_p "`1'"
262
+ local cb_s "`2'"
263
+ local cbngrid `cbgrid'
264
+ if ("`cb'"=="") local cbngrid=0
265
+ if ("`cb_p'"==""|"`cb_p'"=="T") local cb_p=.
266
+ if ("`cb_s'"=="") local cb_s `cb_p'
267
+
268
+ * Add warnings about degrees for estimation and inference
269
+ if ("`selection'"=="J") {
270
+ if ("`ci_p'"!=".") {
271
+ if (`ci_p'<=`dots_p') {
272
+ local ci_p=`dots_p'+1
273
+ local ci_s=`ci_p'
274
+ di as text "Warning: Degree for ci() has been changed. It must be greater than the degree for dots()."
275
+ }
276
+ }
277
+ if ("`cb_p'"!=".") {
278
+ if (`cb_p'<=`dots_p') {
279
+ local cb_p=`dots_p'+1
280
+ local cb_s=`cb_p'
281
+ di as text "Warning: Degree for cb() has been changed. It must be greater than the degree for dots()."
282
+ }
283
+ }
284
+ }
285
+ if ("`selection'"=="NA") {
286
+ if ("`ci'"!=""|"`cb'"!="") {
287
+ di as text "Warning: Confidence intervals/bands are valid when nbins() is much larger than IMSE-optimal choice."
288
+ }
289
+ }
290
+ * if selection==P, compare ci_p/cb_p with P_opt later
291
+
292
+ * poly fit
293
+ local polyregngrid `polyreggrid'
294
+ local polyregcingrid `polyregcigrid'
295
+ if ("`polyreg'"!="") {
296
+ confirm integer n `polyreg'
297
+ }
298
+ else {
299
+ local polyregngrid=0
300
+ }
301
+
302
+ * range of x axis and y axis?
303
+ tokenize `plotxrange'
304
+ local min_xr "`1'"
305
+ local max_xr "`2'"
306
+ tokenize `plotyrange'
307
+ local min_yr "`1'"
308
+ local max_yr "`2'"
309
+
310
+
311
+ * Simuls
312
+ local simsngrid=`simsgrid'
313
+
314
+ * Record if nbins specified by users, set default
315
+ local nbins_full `nbins' /* local save common nbins */
316
+ if ("`selection'"=="NA") local binselectmethod "User-specified"
317
+ else {
318
+ if ("`binsmethod'"=="DPI") local binselectmethod "IMSE-optimal plug-in choice"
319
+ if ("`binsmethod'"=="ROT") local binselectmethod "IMSE-optimal rule-of-thumb choice"
320
+ if ("`selection'"=="J") local binselectmethod "`binselectmethod' (select # of bins)"
321
+ if ("`selection'"=="P") local binselectmethod "`binselectmethod' (select degree and smoothness)"
322
+ }
323
+
324
+ * Mass point check?
325
+ if ("`masspoints'"=="") {
326
+ local massadj "T"
327
+ local localcheck "T"
328
+ }
329
+ else if ("`masspoints'"=="off") {
330
+ local massadj "F"
331
+ local localcheck "F"
332
+ }
333
+ else if ("`masspoints'"=="noadjust") {
334
+ local massadj "F"
335
+ local localcheck "T"
336
+ }
337
+ else if ("`masspoints'"=="nolocalcheck") {
338
+ local massadj "T"
339
+ local localcheck "F"
340
+ }
341
+ else if ("`masspoints'"=="veryfew") {
342
+ local fewmasspoints "T" /* count mass point, but turn off checks */
343
+ }
344
+
345
+ * extract dfcheck
346
+ if ("`dfcheck'"=="") local dfcheck 20 30
347
+ tokenize `dfcheck'
348
+ local dfcheck_n1 "`1'"
349
+ local dfcheck_n2 "`2'"
350
+
351
+ * evaluate at w from another dataset?
352
+ if (`"`at'"'!=`""'&`"`at'"'!=`"mean"'&`"`at'"'!=`"median"'&`"`at'"'!=`"0"') local atwout "user"
353
+
354
+ * use gtools commands instead?
355
+ if ("`usegtools'"=="off") local usegtools ""
356
+ if ("`usegtools'"=="on") local usegtools usegtools
357
+ if ("`usegtools'"!="") {
358
+ capture which gtools
359
+ if (_rc) {
360
+ di as error "Gtools package not installed."
361
+ exit
362
+ }
363
+ local localcheck "F"
364
+ local sel_gtools "on"
365
+ * use gstats tab instead of tabstat/collapse
366
+ * use gquantiles instead of _pctile
367
+ * use gunique instead of binsreg_uniq
368
+ * use fasterxtile instead of irecode (within binsreg_irecode)
369
+ * shut down local checks & do not sort
370
+ }
371
+
372
+ *************************
373
+ **** error checks *******
374
+ *************************
375
+ if (`deriv'<0) {
376
+ di as error "derivative incorrectly specified."
377
+ exit
378
+ }
379
+ if (`deriv'>1&"`transform'"=="T") {
380
+ di as error "deriv cannot be greater than 1 if the conditional probability is requested."
381
+ exit
382
+ }
383
+ if (`dotsngrid'<0|`linengrid'<0|`cingrid'<0|`cbngrid'<0|`simsngrid'<0) {
384
+ di as error "Number of evaluation points incorrectly specified."
385
+ exit
386
+ }
387
+ if (`level'>100|`level'<0) {
388
+ di as error "Confidence level incorrectly specified."
389
+ exit
390
+ }
391
+ if ("`dots_p'"!=".") {
392
+ if (`dots_p'<`dots_s') {
393
+ di as error "p cannot be smaller than s."
394
+ exit
395
+ }
396
+ if (`dots_p'<`deriv') {
397
+ di as error "p for dots cannot be less than deriv."
398
+ exit
399
+ }
400
+ }
401
+ if ("`line_p'"!=".") {
402
+ if (`line_p'<`line_s') {
403
+ di as error "p cannot be smaller than s."
404
+ exit
405
+ }
406
+ if (`line_p'<`deriv') {
407
+ di as error "p for line cannot be less than deriv."
408
+ exit
409
+ }
410
+ }
411
+ if ("`ci_p'"!=".") {
412
+ if (`ci_p'<`ci_s') {
413
+ di as error "p cannot be smaller than s."
414
+ exit
415
+ }
416
+ if (`ci_p'<`deriv') {
417
+ di as error "p for CI cannot be less than deriv."
418
+ exit
419
+ }
420
+ }
421
+ if ("`cb_p'"!=".") {
422
+ if (`cb_p'<`cb_s') {
423
+ di as error "p cannot be smaller than s."
424
+ exit
425
+ }
426
+ if (`cb_p'<`deriv') {
427
+ di as error "p for CB cannot be less than deriv."
428
+ exit
429
+ }
430
+ }
431
+ if ("`polyreg'"!="") {
432
+ if (`polyreg'<`deriv') {
433
+ di as error "polyreg() cannot be less than deriv()."
434
+ exit
435
+ }
436
+ }
437
+
438
+ if (`"`savedata'"'!=`""') {
439
+ if ("`replace'"=="") {
440
+ confirm new file `"`savedata'.dta"'
441
+ }
442
+ if ("`plot'"!="") {
443
+ di as error "Plot cannot be turned off if graph data are requested."
444
+ exit
445
+ }
446
+ }
447
+ if (`polyregcingrid'!=0&"`polyreg'"=="") {
448
+ di as error "polyreg() is missing."
449
+ exit
450
+ }
451
+ if ("`binsmethod'"!="DPI"&"`binsmethod'"!="ROT") {
452
+ di as error "binsmethod incorrectly specified."
453
+ exit
454
+ }
455
+ ******** END error checking ***************************
456
+
457
+ * Mark sample
458
+ preserve
459
+
460
+ * Parse varlist into y_var, x_var and w_var
461
+ tokenize `varlist'
462
+ fvrevar `1', tsonly
463
+ local y_var "`r(varlist)'"
464
+ local y_varname "`1'"
465
+ fvrevar `2', tsonly
466
+ local x_var "`r(varlist)'"
467
+ local x_varname "`2'"
468
+
469
+ macro shift 2
470
+ local w_var "`*'"
471
+ * read eval point for w from another file
472
+ if ("`atwout'"=="user") {
473
+ append using `at'
474
+ }
475
+
476
+ fvrevar `w_var', tsonly
477
+ local w_var "`r(varlist)'"
478
+ local nwvar: word count `w_var'
479
+
480
+ * Save the last obs in a vector and then drop it
481
+ tempname wuser /* a vector used to keep eval for w */
482
+ if ("`atwout'"=="user") {
483
+ mata: st_matrix("`wuser'", st_data(`=_N', "`w_var'"))
484
+ qui drop in `=_N'
485
+ }
486
+
487
+ * Get positions of factor vars
488
+ local indexlist ""
489
+ local i = 1
490
+ foreach v in `w_var' {
491
+ if strpos("`v'", ".") == 0 {
492
+ local indexlist `indexlist' `i'
493
+ }
494
+ local ++i
495
+ }
496
+
497
+ * add a default for at
498
+ if (`"`at'"'==""&`nwvar'>0) {
499
+ local at "mean"
500
+ }
501
+
502
+ marksample touse
503
+ markout `touse' `by', strok
504
+ qui keep if `touse'
505
+ local nsize=_N /* # of rows in the original dataset */
506
+
507
+ if ("`usegtools'"==""&("`masspoints'"!="off"|"`binspos'"=="QS")) {
508
+ if ("`:sortedby'"!="`x_var'") {
509
+ di as text in gr "Sorting dataset on `x_varname'..."
510
+ di as text in gr "Note: This step is omitted if dataset already sorted by `x_varname'."
511
+ sort `x_var', stable
512
+ }
513
+ local sorted "sorted"
514
+ }
515
+
516
+ if ("`wtype'"=="f") qui sum `x_var' `wt', meanonly
517
+ else qui sum `x_var', meanonly
518
+
519
+ local xmin=r(min)
520
+ local xmax=r(max)
521
+ local Ntotal=r(N) /* total sample size, with wt */
522
+ * define the support of plot
523
+ if ("`plotxrange'"!="") {
524
+ local xsc `plotxrange'
525
+ if (wordcount("`xsc'")==1) local xsc `xsc' `xmax'
526
+ }
527
+ else local xsc `xmin' `xmax'
528
+
529
+ * Effective sample size
530
+ local eN=`nsize'
531
+ * DO NOT check mass points and clusters outside loop unless needed
532
+
533
+ * Check number of unique byvals & create local storing byvals
534
+ local byvarname `by'
535
+ if "`by'"!="" {
536
+ capture confirm numeric variable `by'
537
+ if _rc {
538
+ local bystring "T"
539
+ * generate a numeric version
540
+ tempvar by
541
+ tempname bylabel
542
+ qui egen `by'=group(`byvarname'), lname(`bylabel')
543
+ }
544
+
545
+ local bylabel `:value label `by'' /* catch value labels for numeric by-vars too */
546
+
547
+ tempname byvalmatrix
548
+ qui tab `by', nofreq matrow(`byvalmatrix')
549
+
550
+ local bynum=r(r)
551
+ forvalues i=1/`bynum' {
552
+ local byvals `byvals' `=`byvalmatrix'[`i',1]'
553
+ }
554
+ }
555
+ else local bynum=1
556
+
557
+ * Default colors, symbols, linepatterns
558
+ if (`"`bycolors'"'==`""') local bycolors ///
559
+ navy maroon forest_green dkorange teal cranberry lavender ///
560
+ khaki sienna emidblue emerald brown erose gold bluishgray
561
+ if (`"`bysymbols'"'==`""') local bysymbols ///
562
+ O D T S + X A a | V o d s t x
563
+ if (`"`bylpatterns'"'==`""') {
564
+ forval i=1/`bynum' {
565
+ local bylpatterns `bylpatterns' solid
566
+ }
567
+ }
568
+
569
+ * Temp name in MATA
570
+ tempname xvec yvec byvec cluvec binedges
571
+ mata: `xvec'=st_data(., "`x_var'"); `yvec'=st_data(.,"`y_var'"); `byvec'=.; `cluvec'=.
572
+
573
+ *******************************************************
574
+ *** Mass point counting *******************************
575
+ tempname Ndistlist Nclustlist mat_imse_var_rot mat_imse_bsq_rot mat_imse_var_dpi mat_imse_bsq_dpi
576
+ mat `Ndistlist'=J(`bynum',1,.)
577
+ mat `Nclustlist'=J(`bynum',1,.)
578
+ * Matrices saving imse
579
+ mat `mat_imse_var_rot'=J(`bynum',1,.)
580
+ mat `mat_imse_bsq_rot'=J(`bynum',1,.)
581
+ mat `mat_imse_var_dpi'=J(`bynum',1,.)
582
+ mat `mat_imse_bsq_dpi'=J(`bynum',1,.)
583
+
584
+ if (`bynum'>1) mata: `byvec'=st_data(.,"`by'")
585
+ if ("`clusterON'"=="T") mata: `cluvec'=st_data(.,"`clustervar'")
586
+
587
+ ********************************************************
588
+ ********** Bins, based on FULL sample ******************
589
+ ********************************************************
590
+ * knotlist: inner knot seq; knotlistON: local, knot available before loop
591
+
592
+ tempname fullkmat /* matrix name for saving knots based on the full sample */
593
+
594
+ * Extract user-specified knot list
595
+ if ("`binspos'"!="ES"&"`binspos'"!="QS") {
596
+ capture numlist "`binspos'", ascending
597
+ if (_rc==0) {
598
+ local knotlistON "T"
599
+ local knotlist `binspos'
600
+ local nbins: word count `knotlist'
601
+ local first: word 1 of `knotlist'
602
+ local last: word `nbins' of `knotlist'
603
+ if (`first'<=`xmin'|`last'>=`xmax') {
604
+ di as error "Inner knots specified out of allowed range."
605
+ exit
606
+ }
607
+ else {
608
+ local nbins=`nbins'+1
609
+ local nbins_full `nbins'
610
+ local pos "user"
611
+
612
+ foreach el of local knotlist {
613
+ mat `fullkmat'=(nullmat(`fullkmat') \ `el')
614
+ }
615
+ mat `fullkmat'=(`xmin' \ `fullkmat' \ `xmax')
616
+ }
617
+ }
618
+ else {
619
+ di as error "Numeric list incorrectly specified in binspos()."
620
+ exit
621
+ }
622
+ }
623
+
624
+ * Discrete x?
625
+ if ("`fewmasspoints'"!="") local fullfewobs "T"
626
+
627
+ * Bin selection using the whole sample if
628
+ if ("`fullfewobs'"==""&"`selection'"!="NA"&(("`by'"=="")|(("`by'"!="")&("`samebinsby'"!="")))) {
629
+ local selectfullON "T"
630
+ }
631
+
632
+ if ("`selectfullON'"=="T") {
633
+ local Ndist=.
634
+ if ("`massadj'"=="T") {
635
+ if ("`usegtools'"=="") {
636
+ mata: `binedges'=binsreg_uniq(`xvec', ., 1, "Ndist")
637
+ mata: mata drop `binedges'
638
+ }
639
+ else {
640
+ qui gunique `x_var'
641
+ local Ndist=r(unique)
642
+ }
643
+ local eN=min(`eN', `Ndist')
644
+ }
645
+ * # of clusters
646
+ local Nclust=.
647
+ if ("`clusterON'"=="T") {
648
+ if ("`usegtools'"=="") {
649
+ mata: st_local("Nclust", strofreal(rows(uniqrows(`cluvec'))))
650
+ }
651
+ else {
652
+ qui gunique `clustervar'
653
+ local Nclust=r(unique)
654
+ }
655
+ local eN=min(`eN', `Nclust') /* effective sample size */
656
+ }
657
+
658
+
659
+ * Check effective sample size
660
+ if ("`dots_p'"==".") local dotspcheck=6
661
+ else local dotspcheck=`dots_p'
662
+ * Check effective sample size
663
+ if ("`nbinsrot'"==""&(`eN'<=`dfcheck_n1'+`dotspcheck'+1+`qrot')) {
664
+ di as text in gr "Warning: Too small effective sample size for bin selection." ///
665
+ _newline _skip(9) "# of mass points or clusters used and by() option ignored."
666
+ local by ""
667
+ local byvals ""
668
+ local fullfewobs "T"
669
+ local binspos "QS" /* forced to be QS */
670
+ }
671
+ else {
672
+ local randcut1k `randcut'
673
+ if ("`randcut'"=="" & `Ntotal'>5000) {
674
+ local randcut1k=max(5000/`Ntotal', 0.01)
675
+ di as text in gr "Warning: To speed up computation, bin/degree selection uses a subsample of roughly max(5,000, 0.01n) observations if the sample size n>5,000. To use the full sample, set randcut(1)."
676
+ }
677
+ if ("`selection'"=="J") {
678
+ qui binsregselect `y_var' `x_var' `w_var' `wt', deriv(`deriv') bins(`dots_p' `dots_s') nbins(`nbins_full') ///
679
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
680
+ binsmethod(`binsmethod') binspos(`binspos') nbinsrot(`nbinsrot') ///
681
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
682
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
683
+ if (e(nbinsrot_regul)==.) {
684
+ di as error "Bin selection fails."
685
+ exit
686
+ }
687
+ if ("`binsmethod'"=="ROT") {
688
+ local nbins=e(nbinsrot_regul)
689
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
690
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
691
+ }
692
+ else if ("`binsmethod'"=="DPI") {
693
+ local nbins=e(nbinsdpi)
694
+ mat `mat_imse_var_dpi'=J(`bynum',1,e(imse_var_dpi))
695
+ mat `mat_imse_bsq_dpi'=J(`bynum',1,e(imse_bsq_dpi))
696
+ if (`nbins'==.) {
697
+ local nbins=e(nbinsrot_regul)
698
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
699
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
700
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
701
+ }
702
+ }
703
+ }
704
+ else if ("`selection'"=="P") {
705
+ qui binsregselect `y_var' `x_var' `w_var' `wt', deriv(`deriv') nbins(`nbins_full') ///
706
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
707
+ pselect(`plist') sselect(`slist') ///
708
+ binsmethod(`binsmethod') binspos(`binspos') nbinsrot(`nbinsrot') ///
709
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
710
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
711
+ if (e(prot_regul)==.) {
712
+ di as error "bin selection fails."
713
+ exit
714
+ }
715
+ if ("`binsmethod'"=="ROT") {
716
+ local binsp=e(prot_regul)
717
+ local binss=e(srot_regul)
718
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
719
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
720
+ }
721
+ else if ("`binsmethod'"=="DPI") {
722
+ local binsp=e(pdpi)
723
+ local binss=e(sdpi)
724
+ mat `mat_imse_var_dpi'=J(`bynum',1,e(imse_var_dpi))
725
+ mat `mat_imse_bsq_dpi'=J(`bynum',1,e(imse_bsq_dpi))
726
+ if (`binsp'==.) {
727
+ local binsp=e(prot_regul)
728
+ local binss=e(srot_regul)
729
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
730
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
731
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
732
+ }
733
+ }
734
+ if ("`dots'"=="T"|"`dots'"=="") {
735
+ local dots_p=`binsp'
736
+ local dots_s=`binss'
737
+ }
738
+ if ("`line'"=="T") {
739
+ local line_p=`binsp'
740
+ local line_s=`binss'
741
+ }
742
+ if ("`ci'"!="T"&"`ci'"!="") {
743
+ if (`ci_p'<=`binsp') {
744
+ local ci_p=`binsp'+1
745
+ local ci_s=`ci_p'
746
+ di as text "Warning: Degree for ci() has been changed. It must be greater than the IMSE-optimal degree."
747
+ }
748
+ }
749
+ if ("`ci'"=="T") {
750
+ local ci_p=`binsp'+1
751
+ local ci_s=`binss'+1
752
+ }
753
+ if ("`cb'"!="T"&"`cb'"!="") {
754
+ if (`cb_p'<=`binsp') {
755
+ local cb_p=`binsp'+1
756
+ local cb_s=`cb_p'
757
+ di as text "Warning: Degree for cb() has been changed. It must be greater than the IMSE-optimal degree."
758
+ }
759
+ }
760
+ if ("`cb'"=="T") {
761
+ local cb_p=`binsp'+1
762
+ local cb_s=`binss'+1
763
+ }
764
+ }
765
+ }
766
+ }
767
+
768
+ if (("`selectfullON'"=="T"|("`selection'"=="NA"&"`samebinsby'"!=""))&"`fullfewobs'"=="") {
769
+ * Save in a knot list
770
+ local knotlistON "T"
771
+ local nbins_full=`nbins'
772
+ if ("`binspos'"=="ES") {
773
+ local stepsize=(`xmax'-`xmin')/`nbins'
774
+ forvalues i=1/`=`nbins'+1' {
775
+ mat `fullkmat'=(nullmat(`fullkmat') \ `=`xmin'+`stepsize'*(`i'-1)')
776
+ }
777
+ }
778
+ else if ("`binspos'"=="QS") {
779
+ if (`nbins'==1) mat `fullkmat'=(`xmin' \ `xmax')
780
+ else {
781
+ binsreg_pctile `x_var' `wt', nq(`nbins') `usegtools'
782
+ mat `fullkmat'=(`xmin' \ r(Q) \ `xmax')
783
+ }
784
+ }
785
+ }
786
+
787
+ *** Placement name, for display ************
788
+ if ("`pos'"=="user") {
789
+ local binselectmethod "User-specified"
790
+ local placement "User-specified"
791
+ }
792
+ else if ("`binspos'"=="ES") {
793
+ local placement "Evenly-spaced"
794
+ }
795
+ else if ("`binspos'"=="QS") {
796
+ local placement "Quantile-spaced"
797
+ }
798
+
799
+ * NOTE: ALL checkings are put within the loop
800
+
801
+ * Set seed
802
+ if ("`simsseed'"!="") set seed `simsseed'
803
+
804
+ * alpha quantile (for two-sided CI)
805
+ local alpha=(100-(100-`level')/2)/100
806
+
807
+ ***************************************************************************
808
+ *************** Preparation before loop************************************
809
+ ***************************************************************************
810
+
811
+ ********** Prepare vars for plotting ********************
812
+ * names for mata objects storing graph data
813
+ * plotmat: final output (defined outside);
814
+ * plotmatby: output for each group
815
+ tempname plotmat plotmatby xsub ysub byindex xcatsub
816
+ tempname Xm Xm0 mata_fit mata_se /* temp name for mata obj */
817
+
818
+ * count the number of requested columns, record the positions
819
+ local ncolplot=1 /* 1st col reserved for group */
820
+ if ("`plot'"=="") {
821
+ if (`dotsntot'!=0) {
822
+ local dots_start=`ncolplot'+1
823
+ local dots_end=`ncolplot'+4
824
+ local ncolplot=`ncolplot'+4
825
+ }
826
+ if (`linengrid'!=0&"`fullfewobs'"=="") {
827
+ local line_start=`ncolplot'+1
828
+ local line_end=`ncolplot'+4
829
+ local ncolplot=`ncolplot'+4
830
+ }
831
+ if (`polyregngrid'!=0) {
832
+ local poly_start=`ncolplot'+1
833
+ local poly_end=`ncolplot'+4
834
+ local ncolplot=`ncolplot'+4
835
+ if (`polyregcingrid'!=0) {
836
+ local polyci_start=`ncolplot'+1
837
+ local polyci_end=`ncolplot'+5
838
+ local ncolplot=`ncolplot'+5
839
+ }
840
+ }
841
+ if (`cintot'!=0) {
842
+ local ci_start=`ncolplot'+1
843
+ local ci_end=`ncolplot'+5
844
+ local ncolplot=`ncolplot'+5
845
+ }
846
+ if (`cbngrid'!=0&"`fullfewobs'"=="") {
847
+ local cb_start=`ncolplot'+1
848
+ local cb_end=`ncolplot'+5
849
+ local ncolplot=`ncolplot'+5
850
+ }
851
+ }
852
+ mata: `plotmat'=J(0,`ncolplot',.)
853
+
854
+ * mark the (varying) last row (for plotting)
855
+ local bylast=0
856
+ *******************************************************************
857
+ * temp var: bin id
858
+ tempvar xcat
859
+ qui gen `xcat'=. in 1
860
+
861
+ * matrix names, for returns
862
+ tempname Nlist nbinslist cvallist
863
+
864
+ * local vars, for plotting
865
+ local counter_by=1
866
+ local plotnum=0 /* count the number of series, for legend */
867
+ if ("`by'"=="") local noby="noby"
868
+ local byvalnamelist "" /* save group name (value) */
869
+ local plotcmd "" /* plotting cmd */
870
+
871
+ ***************************************************************************
872
+ ******************* Now, enter the loop ***********************************
873
+ ***************************************************************************
874
+ foreach byval in `byvals' `noby' {
875
+ local conds ""
876
+ if ("`by'"!="") {
877
+ local conds "if `by'==`byval'" /* with "if" */
878
+ if ("`bylabel'"=="") local byvalname=`byval'
879
+ else {
880
+ local byvalname `: label `bylabel' `byval''
881
+ }
882
+ local byvalnamelist `" `byvalnamelist' `"`byvalname'"' "'
883
+ }
884
+ if (`bynum'>1) {
885
+ mata: `byindex'=`byvec':==`byval'
886
+ mata: `xsub'=select(`xvec',`byindex'); `ysub'=select(`yvec', `byindex')
887
+ }
888
+ else {
889
+ mata: `xsub'=`xvec'; `ysub'=`yvec'
890
+ }
891
+
892
+ * Subsample size
893
+ if ("`wtype'"=="f") sum `x_var' `conds' `wt', meanonly
894
+ else sum `x_var' `conds', meanonly
895
+
896
+ local xmin=r(min)
897
+ local xmax=r(max)
898
+ local N=r(N)
899
+ mat `Nlist'=(nullmat(`Nlist') \ `N')
900
+
901
+ * Effective sample size
902
+ if (`bynum'==1) local eN=`nsize'
903
+ else {
904
+ if ("`wtype'"!="f") local eN=r(N)
905
+ else {
906
+ qui count `conds'
907
+ local eN=r(N)
908
+ }
909
+ }
910
+
911
+ local Ndist=.
912
+ if ("`massadj'"=="T") {
913
+ if ("`usegtools'"=="") {
914
+ mata: `binedges'=binsreg_uniq(`xsub', ., 1, "Ndist")
915
+ mata: mata drop `binedges'
916
+ }
917
+ else {
918
+ qui gunique `x_var' `conds'
919
+ local Ndist=r(unique)
920
+ }
921
+ local eN=min(`eN', `Ndist')
922
+ mat `Ndistlist'[`counter_by',1]=`Ndist'
923
+ }
924
+
925
+ * # of clusters
926
+ local Nclust=.
927
+ if ("`clusterON'"=="T") {
928
+ if (`bynum'==1) {
929
+ if ("`usegtools'"=="") {
930
+ mata: st_local("Nclust", strofreal(rows(uniqrows(`cluvec'))))
931
+ }
932
+ else {
933
+ qui gunique `clustervar'
934
+ local Nclust=r(unique)
935
+ }
936
+ }
937
+ else {
938
+ if ("`usegtools'"=="") {
939
+ mata: st_local("Nclust", strofreal(rows(uniqrows(select(`cluvec', `byindex')))))
940
+ }
941
+ else {
942
+ qui gunique `clustervar' `conds'
943
+ local Nclust=r(unique)
944
+ }
945
+ }
946
+ local eN=min(`eN', `Nclust') /* effective SUBsample size */
947
+ mat `Nclustlist'[`counter_by',1]=`Nclust'
948
+ }
949
+
950
+ *********************************************************
951
+ ************** Prepare bins, within loop ****************
952
+ *********************************************************
953
+ if ("`pos'"!="user") local pos `binspos' /* initialize pos */
954
+ * Selection?
955
+ if ("`selection'"!="NA"&"`knotlistON'"!="T"&"`fullfewobs'"=="") {
956
+ * Check effective sample size
957
+ if ("`dots_p'"==".") local dotspcheck=6
958
+ else local dotspcheck=`dots_p'
959
+ if ("`nbinsrot'"==""&(`eN'<=`dfcheck_n1'+`dotspcheck'+1+`qrot')) {
960
+ di as text in gr "Warning: Too small effective sample size for bin selection." ///
961
+ _newline _skip(9) "# of mass points or clusters used."
962
+ local fewobs "T"
963
+ local nbins=`eN'
964
+ local pos "QS" /* forced to be QS */
965
+ }
966
+ else {
967
+ local randcut1k `randcut'
968
+ if ("`randcut'"=="" & `N'>5000) {
969
+ local randcut1k=max(5000/`N', 0.01)
970
+ di as text in gr "Warning: To speed up computation, bin/degree selection uses a subsample of roughly max(5,000, 0.01n) observations if the sample size n>5,000. To use the full sample, set randcut(1)."
971
+ }
972
+ if ("`selection'"=="J") {
973
+ qui binsregselect `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
974
+ bins(`dots_p' `dots_s') nbins(`nbins_full') ///
975
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
976
+ binsmethod(`binsmethod') binspos(`pos') nbinsrot(`nbinsrot') ///
977
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
978
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
979
+ if (e(nbinsrot_regul)==.) {
980
+ di as error "Bin selection fails."
981
+ exit
982
+ }
983
+ if ("`binsmethod'"=="ROT") {
984
+ local nbins=e(nbinsrot_regul)
985
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
986
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
987
+ }
988
+ else if ("`binsmethod'"=="DPI") {
989
+ local nbins=e(nbinsdpi)
990
+ mat `mat_imse_bsq_dpi'[`counter_by',1]=e(imse_bsq_dpi)
991
+ mat `mat_imse_var_dpi'[`counter_by',1]=e(imse_var_dpi)
992
+ if (`nbins'==.) {
993
+ local nbins=e(nbinsrot_regul)
994
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
995
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
996
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
997
+ }
998
+ }
999
+ }
1000
+ else if ("`selection'"=="P") {
1001
+ qui binsregselect `y_var' `x_var' `w_var' `wt', deriv(`deriv') nbins(`nbins_full') ///
1002
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
1003
+ pselect(`plist') sselect(`slist') ///
1004
+ binsmethod(`binsmethod') binspos(`binspos') nbinsrot(`nbinsrot') ///
1005
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
1006
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
1007
+ if (e(prot_regul)==.) {
1008
+ di as error "Bin selection fails."
1009
+ exit
1010
+ }
1011
+ if ("`binsmethod'"=="ROT") {
1012
+ local binsp=e(prot_regul)
1013
+ local binss=e(srot_regul)
1014
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
1015
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
1016
+ }
1017
+ else if ("`binsmethod'"=="DPI") {
1018
+ local binsp=e(pdpi)
1019
+ local binss=e(sdpi)
1020
+ mat `mat_imse_bsq_dpi'[`counter_by',1]=e(imse_bsq_dpi)
1021
+ mat `mat_imse_var_dpi'[`counter_by',1]=e(imse_var_dpi)
1022
+ if (`binsp'==.) {
1023
+ local binsp=e(prot_regul)
1024
+ local binss=e(srot_regul)
1025
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
1026
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
1027
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
1028
+ }
1029
+ }
1030
+ if ("`dots'"=="T"|"`dots'"=="") {
1031
+ local dots_p=`binsp'
1032
+ local dots_s=`binss'
1033
+ }
1034
+ if ("`line'"=="T") {
1035
+ local line_p=`binsp'
1036
+ local line_s=`binss'
1037
+ }
1038
+ if ("`ci'"!="T"&"`ci'"!="") {
1039
+ if (`ci_p'<=`binsp') {
1040
+ local ci_p=`binsp'+1
1041
+ local ci_s=`ci_p'
1042
+ di as text "Warning: Degree for ci() has been changed. It must be greater than the IMSE-optimal degree."
1043
+ }
1044
+ }
1045
+ if ("`ci'"=="T") {
1046
+ local ci_p=`binsp'+1
1047
+ local ci_s=`binss'+1
1048
+ }
1049
+ if ("`cb'"!="T"&"`cb'"!="") {
1050
+ if (`cb_p'<=`binsp') {
1051
+ local cb_p=`binsp'+1
1052
+ local cb_s=`cb_p'
1053
+ di as text "Warning: Degree for cb() has been changed. It must be greater than the IMSE-optimal degree."
1054
+ }
1055
+ }
1056
+ if ("`cb'"=="T") {
1057
+ local cb_p=`binsp'+1
1058
+ local cb_s=`binss'+1
1059
+ }
1060
+ }
1061
+ }
1062
+ }
1063
+
1064
+ if ("`selection'"=="NA"|"`knotlistON'"=="T") local nbins=`nbins_full' /* add the universal nbins */
1065
+ *if ("`knotlistON'"=="T") local nbins=`nbins_full'
1066
+ if ("`fullfewobs'"!="") {
1067
+ local fewobs "T"
1068
+ local nbins=`eN'
1069
+ }
1070
+
1071
+ ******************************************************
1072
+ * Check effective sample size for each case **********
1073
+ ******************************************************
1074
+ if ("`fewobs'"!="T") {
1075
+ if ((`nbins'-1)*(`dots_p'-`dots_s'+1)+`dots_p'+1+`dfcheck_n2'>=`eN') {
1076
+ local fewobs "T" /* even though ROT available, treat it as few obs case */
1077
+ local nbins=`eN'
1078
+ local pos "QS"
1079
+ di as text in gr "Warning: Too small effective sample size for dots. # of mass points or clusters used."
1080
+ }
1081
+ if ("`line_p'"!=".") {
1082
+ if ((`nbins'-1)*(`line_p'-`line_s'+1)+`line_p'+1+`dfcheck_n2'>=`eN') {
1083
+ local line_fewobs "T"
1084
+ di as text in gr "Warning: Too small effective sample size for line."
1085
+ }
1086
+ }
1087
+ if ("`ci_p'"!=".") {
1088
+ if ((`nbins'-1)*(`ci_p'-`ci_s'+1)+`ci_p'+1+`dfcheck_n2'>=`eN') {
1089
+ local ci_fewobs "T"
1090
+ di as text in gr "Warning: Too small effective sample size for CI."
1091
+ }
1092
+ }
1093
+ if ("`cb_p'"!=".") {
1094
+ if ((`nbins'-1)*(`cb_p'-`cb_s'+1)+`cb_p'+1+`dfcheck_n2'>=`eN') {
1095
+ local cb_fewobs "T"
1096
+ di as text in gr "Warning: Too small effective sample size for CB."
1097
+ }
1098
+ }
1099
+ }
1100
+
1101
+ if ("`polyreg'"!="") {
1102
+ if (`polyreg'+1>=`eN') {
1103
+ local polyreg_fewobs "T"
1104
+ di as text in gr "Warning: Too small effective sample size for polynomial fit."
1105
+ }
1106
+ }
1107
+
1108
+ * Generate category variable for data and save knot in matrix
1109
+ tempname kmat
1110
+
1111
+ if ("`knotlistON'"=="T") {
1112
+ mat `kmat'=`fullkmat'
1113
+ if ("`fewobs'"=="T"&"`eN'"!="`Ndist'") {
1114
+ if (`nbins'==1) mat `kmat'=(`xmin' \ `xmax')
1115
+ else {
1116
+ binsreg_pctile `x_var' `conds' `wt', nq(`nbins') `usegtools'
1117
+ mat `kmat'=(`xmin' \ r(Q) \ `xmax')
1118
+ }
1119
+ }
1120
+ }
1121
+ else {
1122
+ if ("`fewmasspoints'"==""&("`fewobs'"!="T"|"`eN'"!="`Ndist'")) {
1123
+ if ("`pos'"=="ES") {
1124
+ local stepsize=(`xmax'-`xmin')/`nbins'
1125
+ forvalues i=1/`=`nbins'+1' {
1126
+ mat `kmat'=(nullmat(`kmat') \ `=`xmin'+`stepsize'*(`i'-1)')
1127
+ }
1128
+ }
1129
+ else {
1130
+ if (`nbins'==1) mat `kmat'=(`xmin' \ `xmax')
1131
+ else {
1132
+ binsreg_pctile `x_var' `conds' `wt', nq(`nbins') `usegtools'
1133
+ mat `kmat'=(`xmin' \ r(Q) \ `xmax')
1134
+ }
1135
+ }
1136
+ }
1137
+ }
1138
+
1139
+ * Renew knot list if few mass points
1140
+ if (("`fewobs'"=="T"&"`eN'"=="`Ndist'")|"`fewmasspoints'"!="") {
1141
+ qui tab `x_var' `conds', matrow(`kmat')
1142
+ if ("`fewmasspoints'"!="") {
1143
+ local nbins=rowsof(`kmat')
1144
+ local Ndist=`nbins'
1145
+ local eN=`Ndist'
1146
+ }
1147
+ }
1148
+ else {
1149
+ mata: st_matrix("`kmat'", (`xmin' \ uniqrows(st_matrix("`kmat'")[|2 \ `=`nbins'+1'|])))
1150
+ if (`nbins'!=rowsof(`kmat')-1) {
1151
+ di as text in gr "Warning: Repeated knots. Some bins dropped."
1152
+ local nbins=rowsof(`kmat')-1
1153
+ }
1154
+
1155
+ binsreg_irecode `x_var' `conds', knotmat(`kmat') bin(`xcat') ///
1156
+ `usegtools' nbins(`nbins') pos(`pos') knotliston(`knotlistON')
1157
+
1158
+ mata: `xcatsub'=st_data(., "`xcat'")
1159
+ if (`bynum'>1) {
1160
+ mata: `xcatsub'=select(`xcatsub', `byindex')
1161
+ }
1162
+ }
1163
+
1164
+ *************************************************
1165
+ **** Check for empty bins ***********************
1166
+ *************************************************
1167
+ mata: `binedges'=. /* initialize */
1168
+ if ("`fewobs'"!="T"&"`localcheck'"=="T") {
1169
+ mata: st_local("Ncat", strofreal(rows(uniqrows(`xcatsub'))))
1170
+ if (`nbins'==`Ncat') {
1171
+ mata: `binedges'=binsreg_uniq(`xsub', `xcatsub', `nbins', "uniqmin")
1172
+ }
1173
+ else {
1174
+ local uniqmin=0
1175
+ di as text in gr "Warning: There are empty bins. Specify a smaller number in nbins()."
1176
+ }
1177
+
1178
+ if ("`dots_p'"!=".") {
1179
+ if (`uniqmin'<`dots_p'+1) {
1180
+ local dots_fewobs "T"
1181
+ di as text in gr "Warning: Some bins have too few distinct x-values for dots."
1182
+ }
1183
+ }
1184
+ if ("`line_p'"!=".") {
1185
+ if (`uniqmin'<`line_p'+1) {
1186
+ local line_fewobs "T"
1187
+ di as text in gr "Warning: Some bins have too few distinct x-values for line."
1188
+ }
1189
+ }
1190
+ if ("`ci_p'"!=".") {
1191
+ if (`uniqmin'<`ci_p'+1) {
1192
+ local ci_fewobs "T"
1193
+ di as text in gr "Warning: Some bins have too few distinct x-values for CI."
1194
+ }
1195
+ }
1196
+ if ("`cb_p'"!=".") {
1197
+ if (`uniqmin'<`cb_p'+1) {
1198
+ local cb_fewobs "T"
1199
+ di as text in gr "Warning: Some bins have too few distinct x-values for CB."
1200
+ }
1201
+ }
1202
+ }
1203
+
1204
+ * Now, save nbins in a list !!!
1205
+ mat `nbinslist'=(nullmat(`nbinslist') \ `nbins')
1206
+
1207
+ **********************************************************
1208
+ **** Count the number of rows needed (within loop!) ******
1209
+ **********************************************************
1210
+ local byfirst=`bylast'+1
1211
+ local byrange=0
1212
+ if ("`fewobs'"!="T") {
1213
+ local dots_nr=`dotsngrid_mean'*`nbins'
1214
+ if (`dotsngrid'!=0) local dots_nr=`dots_nr'+`dotsngrid'*`nbins'+`nbins'-1
1215
+ local ci_nr=`cingrid_mean'*`nbins'
1216
+ if (`cingrid'!=0) local ci_nr=`ci_nr'+`cingrid'*`nbins'+`nbins'-1
1217
+ if (`linengrid'!=0) local line_nr=`linengrid'*`nbins'+`nbins'-1
1218
+ if (`cbngrid'!=0) local cb_nr=`cbngrid'*`nbins'+`nbins'-1
1219
+ if (`polyregngrid'!=0) {
1220
+ local poly_nr=`polyregngrid'*`nbins'+`nbins'-1
1221
+ if (`polyregcingrid'!=0) local polyci_nr=`polyregcingrid'*`nbins'+`nbins'-1
1222
+ }
1223
+ local byrange=max(`dots_nr'+0,`line_nr'+0,`ci_nr'+0,`cb_nr'+0, `poly_nr'+0, `polyci_nr'+0)
1224
+ }
1225
+ else {
1226
+ if ("`eN'"=="`Ndist'") {
1227
+ if (`polyregngrid'!=0) {
1228
+ local poly_nr=`polyregngrid'*(`nbins'-1)+`nbins'-1-1
1229
+ if (`polyregcingrid'!=0) local polyci_nr=`polyregcingrid'*(`nbins'-1)+`nbins'-1-1
1230
+ }
1231
+ }
1232
+ else {
1233
+ if (`polyregngrid'!=0) {
1234
+ local poly_nr=`polyregngrid'*`nbins'+`nbins'-1
1235
+ if (`polyregcingrid'!=0) local polyci_nr=`polyregcingrid'*`nbins'+`nbins'-1
1236
+ }
1237
+ }
1238
+ local byrange=max(`nbins', `poly_nr'+0, `polyci_nr'+0)
1239
+ }
1240
+ local bylast=`bylast'+`byrange'
1241
+ mata: `plotmatby'=J(`byrange',`ncolplot',.)
1242
+ if ("`byval'"!="noby") {
1243
+ mata: `plotmatby'[.,1]=J(`byrange',1,`byval')
1244
+ }
1245
+
1246
+ ************************************************
1247
+ **** START: prepare data for plotting***********
1248
+ ************************************************
1249
+ local plotcmdby ""
1250
+
1251
+ ********************************
1252
+ * adjust w vars
1253
+ tempname wval
1254
+ if (`nwvar'>0) {
1255
+ if (`"`at'"'==`"mean"'|`"`at'"'==`"median"') {
1256
+ matrix `wval'=J(1, `nwvar', 0)
1257
+ tempname wvaltemp mataobj
1258
+ mata: `mataobj'=.
1259
+ foreach wpos in `indexlist' {
1260
+ local wname: word `wpos' of `w_var'
1261
+ if ("`usegtools'"=="") {
1262
+ if ("`wtype'"!="") qui tabstat `wname' `conds' [aw`exp'], stat(`at') save
1263
+ else qui tabstat `wname' `conds', stat(`at') save
1264
+ mat `wvaltemp'=r(StatTotal)
1265
+ }
1266
+ else {
1267
+ qui gstats tabstat `wname' `conds' `wt', stat(`at') matasave("`mataobj'")
1268
+ mata: st_matrix("`wvaltemp'", `mataobj'.getOutputCol(1))
1269
+ }
1270
+ mat `wval'[1,`wpos']=`wvaltemp'[1,1]
1271
+ }
1272
+ mata: mata drop `mataobj'
1273
+ }
1274
+ else if (`"`at'"'==`"0"') {
1275
+ matrix `wval'=J(1,`nwvar',0)
1276
+ }
1277
+ else if ("`atwout'"=="user") {
1278
+ matrix `wval'=`wuser'
1279
+ }
1280
+ }
1281
+
1282
+
1283
+ *************************************************
1284
+ ********** dots and ci for few obs. case ********
1285
+ *************************************************
1286
+ if (`dotsntot'!=0&"`plot'"==""&"`fewobs'"=="T") {
1287
+ di as text in gr "Warning: dots(0 0) is used."
1288
+ if (`deriv'>0) di as text in gr "Warning: deriv(0 0) is used."
1289
+
1290
+ local dots_first=`byfirst'
1291
+ local dots_last=`byfirst'-1+`nbins'
1292
+
1293
+ mata: `plotmatby'[|1,`dots_start'+2 \ `nbins',`dots_start'+2|]=range(1,`nbins',1)
1294
+
1295
+ if ("`eN'"=="`Ndist'") {
1296
+ mata: `plotmatby'[|1,`dots_start' \ `nbins',`dots_start'|]=st_matrix("`kmat'"); ///
1297
+ `plotmatby'[|1,`dots_start'+1 \ `nbins',`dots_start'+1|]=J(`nbins',1,1)
1298
+
1299
+ * Renew knot commalist, each value forms a group
1300
+ local xknot ""
1301
+ forvalues i=1/`nbins' {
1302
+ local xknot `xknot' `kmat'[`i',1]
1303
+ }
1304
+ local xknotcommalist : subinstr local xknot " " ",", all
1305
+ qui replace `xcat'=1+irecode(`x_var',`xknotcommalist') `conds'
1306
+ }
1307
+ else {
1308
+ tempname grid
1309
+ mat `grid'=(`kmat'[1..`nbins',1]+`kmat'[2..`nbins'+1,1])/2
1310
+ mata: `plotmatby'[|1,`dots_start' \ `nbins',`dots_start'|]=st_matrix("`grid'"); ///
1311
+ `plotmatby'[|1,`dots_start'+1 \ `nbins',`dots_start'+1|]=J(`nbins',1,0)
1312
+ }
1313
+
1314
+ local nseries=`nbins'
1315
+ capture logit `y_var' ibn.`xcat' `w_var' `conds' `wt', nocon `vce' `logitopt'
1316
+ tempname fewobs_b fewobs_V
1317
+ if (_rc==0) {
1318
+ mat `fewobs_b'=e(b)
1319
+ mat `fewobs_V'=e(V)
1320
+ mata: binsreg_checkdrop("`fewobs_b'", "`fewobs_V'", `nseries')
1321
+ if (`nwvar'>0) {
1322
+ mat `fewobs_b'=`fewobs_b'[1,1..`nseries']+(`fewobs_b'[1,`=`nseries'+1'..`=`nseries'+`nwvar'']*`wval'')*J(1,`nseries',1)
1323
+ }
1324
+ else {
1325
+ mat `fewobs_b'=`fewobs_b'[1,1..`nseries']
1326
+ }
1327
+ }
1328
+ else {
1329
+ error _rc
1330
+ exit _rc
1331
+ }
1332
+
1333
+ if ("`transform'"=="T") {
1334
+ mata: `plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]=logistic(st_matrix("`fewobs_b'"))'
1335
+ }
1336
+ else {
1337
+ mata: `plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]=st_matrix("`fewobs_b'")'
1338
+ }
1339
+
1340
+ local plotnum=`plotnum'+1
1341
+ local legendnum `legendnum' `plotnum'
1342
+ local col: word `counter_by' of `bycolors'
1343
+ local sym: word `counter_by' of `bysymbols'
1344
+ local plotcond ""
1345
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1346
+ local plotcond `plotcond' if
1347
+ if ("`plotxrange'"!="") {
1348
+ local plotcond `plotcond' dots_x>=`min_xr'
1349
+ if ("`max_xr'"!="") local plotcond `plotcond' &dots_x<=`max_xr'
1350
+ }
1351
+ if ("`plotyrange'"!="") {
1352
+ if ("`plotxrange'"=="") local plotcond `plotcond' dots_fit>=`min_yr'
1353
+ else local plotcond `plotcond' &dots_fit>=`min_yr'
1354
+ if ("`max_yr'"!="") local plotcond `plotcond' &dots_fit<=`max_yr'
1355
+ }
1356
+ }
1357
+
1358
+ local plotcmdby `plotcmdby' (scatter dots_fit dots_x ///
1359
+ `plotcond' in `dots_first'/`dots_last', ///
1360
+ mcolor(`col') msymbol(`sym') `dotsplotopt')
1361
+
1362
+ if (`cintot'!=0) {
1363
+ di as text in gr "Warning: ci(0 0) is used."
1364
+
1365
+ if (`nwvar'>0) {
1366
+ mata: `mata_se'=(I(`nseries'), J(`nseries',1,1)#st_matrix("`wval'"))
1367
+ }
1368
+ else {
1369
+ mata: `mata_se'=I(`nseries')
1370
+ }
1371
+
1372
+ mata: `plotmatby'[|1,`ci_start'+1 \ `nbins',`ci_start'+2|]=`plotmatby'[|1,`dots_start'+1 \ `nbins',`dots_start'+2|]; ///
1373
+ `mata_se'=sqrt(rowsum((`mata_se'*st_matrix("`fewobs_V'")):*`mata_se'))
1374
+ if ("`transform'"=="T") {
1375
+ mata: `mata_se'=`mata_se':*(logisticden(st_matrix("`fewobs_b'"))')
1376
+ }
1377
+ mata: `plotmatby'[|1,`ci_start'+3 \ `nbins',`ci_start'+3|]=`plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]-`mata_se'*invnormal(`alpha'); ///
1378
+ `plotmatby'[|1,`ci_start'+4 \ `nbins',`ci_start'+4|]=`plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]+`mata_se'*invnormal(`alpha')
1379
+ mata: mata drop `mata_se'
1380
+
1381
+ local plotnum=`plotnum'+1
1382
+ local lty: word `counter_by' of `bylpatterns'
1383
+ local plotcmdby `plotcmdby' (rcap CI_l CI_r dots_x ///
1384
+ `plotcond' in `dots_first'/`dots_last', ///
1385
+ sort lcolor(`col') lpattern(`lty') `ciplotopt')
1386
+ }
1387
+ }
1388
+
1389
+ *********************************************
1390
+ **** The following handles the usual case ***
1391
+ *********************************************
1392
+ * Turn on or off?
1393
+ local dotsON ""
1394
+ local lineON ""
1395
+ local polyON ""
1396
+ local ciON ""
1397
+ local cbON ""
1398
+ if (`dotsntot'!=0&"`plot'"==""&"`fewobs'"!="T"&"`dots_fewobs'"!="T") {
1399
+ local dotsON "T"
1400
+ }
1401
+ if (`linengrid'!=0&"`plot'"==""&"`line_fewobs'"!="T"&"`fewobs'"!="T") {
1402
+ local lineON "T"
1403
+ }
1404
+ if (`polyregngrid'!=0&"`plot'"==""&"`polyreg_fewobs'"!="T") {
1405
+ local polyON "T"
1406
+ }
1407
+ if (`cintot'!=0&"`plot'"==""&"`ci_fewobs'"!="T"&"`fewobs'"!="T") {
1408
+ local ciON "T"
1409
+ }
1410
+ if (`cbngrid'!=0&"`plot'"==""&"`cb_fewobs'"!="T"&"`fewobs'"!="T") {
1411
+ local cbON "T"
1412
+ }
1413
+
1414
+
1415
+ ************************
1416
+ ****** Dots ************
1417
+ ************************
1418
+ tempname xmean
1419
+
1420
+ if ("`dotsON'"=="T") {
1421
+ local dots_first=`byfirst'
1422
+ local dots_last=`byfirst'+`dots_nr'-1
1423
+
1424
+ * fitting
1425
+ tempname dots_b dots_V
1426
+ if (("`dots_p'"=="`ci_p'"&"`dots_s'"=="`ci_s'"&"`ciON'"=="T")| ///
1427
+ ("`dots_p'"=="`cb_p'"&"`dots_s'"=="`cb_s'"&"`cbON'"=="T")) {
1428
+ binslogit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1429
+ p(`dots_p') s(`dots_s') type(dots) `vce' ///
1430
+ xcat(`xcat') kmat(`kmat') dotsmean(`dotsngrid_mean') ///
1431
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1432
+ usereg `sorted' `usegtools' logitopt(`logitopt')
1433
+ }
1434
+ else {
1435
+ binslogit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1436
+ p(`dots_p') s(`dots_s') type(dots) `vce' ///
1437
+ xcat(`xcat') kmat(`kmat') dotsmean(`dotsngrid_mean') ///
1438
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1439
+ `sorted' `usegtools' logitopt(`logitopt')
1440
+ }
1441
+
1442
+ mat `dots_b'=e(bmat)
1443
+ mat `dots_V'=e(Vmat)
1444
+ if (`dotsngrid_mean'!=0) mat `xmean'=e(xmat)
1445
+
1446
+ * prediction
1447
+ if (`dotsngrid_mean'==0) {
1448
+ mata: `plotmatby'[|1,`dots_start' \ `dots_nr',`dots_end'|] = ///
1449
+ binslogit_plotmat("`dots_b'", "`dots_V'", ., "`kmat'", ///
1450
+ `nbins', `dots_p', `dots_s', `deriv', ///
1451
+ "dots", `dotsngrid', "`wval'", `nwvar', ///
1452
+ "`transform'", "`asyvar'")
1453
+ }
1454
+ else {
1455
+ mata: `plotmatby'[|1,`dots_start' \ `dots_nr',`dots_end'|] = ///
1456
+ binslogit_plotmat("`dots_b'", "`dots_V'", ., "`kmat'", ///
1457
+ `nbins', `dots_p', `dots_s', `deriv', ///
1458
+ "dots", `dotsngrid', "`wval'", `nwvar', ///
1459
+ "`transform'", "`asyvar'", "`xmean'")
1460
+ }
1461
+
1462
+ * dots
1463
+ local plotnum=`plotnum'+1
1464
+ if ("`cbON'"=="T") local legendnum `legendnum' `=`plotnum'+1'
1465
+ else {
1466
+ local legendnum `legendnum' `plotnum'
1467
+ }
1468
+ local col: word `counter_by' of `bycolors'
1469
+ local sym: word `counter_by' of `bysymbols'
1470
+ local plotcond ""
1471
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1472
+ local plotcond if
1473
+ if ("`plotxrange'"!="") {
1474
+ local plotcond `plotcond' dots_x>=`min_xr'
1475
+ if ("`max_xr'"!="") local plotcond `plotcond' &dots_x<=`max_xr'
1476
+ }
1477
+ if ("`plotyrange'"!="") {
1478
+ if ("`plotxrange'"=="") local plotcond `plotcond' dots_fit>=`min_yr'
1479
+ else local plotcond `plotcond' &dots_fit>=`min_yr'
1480
+ if ("`max_yr'"!="") local plotcond `plotcond' &dots_fit<=`max_yr'
1481
+ }
1482
+ }
1483
+
1484
+ local plotcmdby `plotcmdby' (scatter dots_fit dots_x ///
1485
+ `plotcond' in `dots_first'/`dots_last', ///
1486
+ mcolor(`col') msymbol(`sym') `dotsplotopt')
1487
+ }
1488
+
1489
+ **********************************************
1490
+ ********************* Line *******************
1491
+ **********************************************
1492
+ if ("`lineON'"=="T") {
1493
+ local line_first=`byfirst'
1494
+ local line_last=`byfirst'-1+`line_nr'
1495
+
1496
+ * fitting
1497
+ tempname line_b line_V
1498
+ capture confirm matrix `dots_b' `dots_V'
1499
+ if ("`line_p'"=="`dots_p'"& "`line_s'"=="`dots_s'" & _rc==0) {
1500
+ matrix `line_b'=`dots_b'
1501
+ matrix `line_V'=`dots_V'
1502
+ }
1503
+ else {
1504
+ if (("`line_p'"=="`ci_p'"&"`line_s'"=="`ci_s'"&"`ciON'"=="T")| ///
1505
+ ("`line_p'"=="`cb_p'"&"`line_s'"=="`cb_s'"&"`cbON'"=="T")) {
1506
+ binslogit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1507
+ p(`line_p') s(`line_s') type(line) `vce' ///
1508
+ xcat(`xcat') kmat(`kmat') dotsmean(0) ///
1509
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1510
+ usereg `sorted' `usegtools' logitopt(`logitopt')
1511
+ }
1512
+ else {
1513
+ binslogit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1514
+ p(`line_p') s(`line_s') type(line) `vce' ///
1515
+ xcat(`xcat') kmat(`kmat') dotsmean(0) ///
1516
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1517
+ `sorted' `usegtools' logitopt(`logitopt')
1518
+ }
1519
+ mat `line_b'=e(bmat)
1520
+ mat `line_V'=e(Vmat)
1521
+ }
1522
+
1523
+ * prediction
1524
+ mata: `plotmatby'[|1,`line_start' \ `line_nr',`line_end'|] = ///
1525
+ binslogit_plotmat("`line_b'", "`line_V'", ., "`kmat'", ///
1526
+ `nbins', `line_p', `line_s', `deriv', ///
1527
+ "line", `linengrid', "`wval'", `nwvar', "`transform'", "`asyvar'")
1528
+
1529
+ * line
1530
+ local plotnum=`plotnum'+1
1531
+ local col: word `counter_by' of `bycolors'
1532
+ local lty: word `counter_by' of `bylpatterns'
1533
+ local plotcond ""
1534
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1535
+ local plotcond if
1536
+ if ("`plotxrange'"!="") {
1537
+ local plotcond `plotcond' line_x>=`min_xr'
1538
+ if ("`max_xr'"!="") local plotcond `plotcond' &line_x<=`max_xr'
1539
+ }
1540
+ if ("`plotyrange'"!="") {
1541
+ if ("`plotxrange'"=="") local plotcond `plotcond' line_fit>=`min_yr'
1542
+ else local plotcond `plotcond' &line_fit>=`min_yr'
1543
+ if ("`max_yr'"!="") local plotcond `plotcond' &(line_fit<=`max_yr'|line_fit==.)
1544
+ }
1545
+ }
1546
+
1547
+ local plotcmdby `plotcmdby' (line line_fit line_x ///
1548
+ `plotcond' in `line_first'/`line_last', sort cmissing(n) ///
1549
+ lcolor(`col') lpattern(`lty') `lineplotopt')
1550
+
1551
+ }
1552
+
1553
+ ***********************************
1554
+ ******* Polynomial fit ************
1555
+ ***********************************
1556
+ if ("`polyON'"=="T") {
1557
+ if (`nwvar'>0) {
1558
+ di as text "Note: When additional covariates w are included, the polynomial fit may not always be close to the binscatter fit."
1559
+ }
1560
+
1561
+ local poly_first=`byfirst'
1562
+ local poly_last=`byfirst'-1+`poly_nr'
1563
+
1564
+ mata:`plotmatby'[|1,`poly_start' \ `poly_nr',`poly_start'+2|]=binsreg_grids("`kmat'",`polyregngrid')
1565
+
1566
+ local poly_series ""
1567
+ forval i=0/`polyreg' {
1568
+ tempvar x_var_`i'
1569
+ qui gen `x_var_`i''=`x_var'^`i' `conds'
1570
+ local poly_series `poly_series' `x_var_`i''
1571
+ }
1572
+
1573
+ capture logit `y_var' `poly_series' `w_var' `conds' `wt', nocon `vce' `logitopt'
1574
+ * store results
1575
+ tempname poly_b poly_V poly_adjw
1576
+ if (_rc==0) {
1577
+ matrix `poly_b'=e(b)
1578
+ matrix `poly_V'=e(V)
1579
+ }
1580
+ else {
1581
+ error _rc
1582
+ exit _rc
1583
+ }
1584
+
1585
+ * Data for derivative
1586
+ mata: `Xm'=J(`poly_nr',0,.); `Xm0'=J(`poly_nr',0,.)
1587
+ forval i=`deriv'/`polyreg' {
1588
+ mata: `Xm'=(`Xm', ///
1589
+ `plotmatby'[|1,`poly_start' \ `poly_nr',`poly_start'|]:^(`i'-`deriv')* ///
1590
+ factorial(`i')/factorial(`i'-`deriv'))
1591
+ }
1592
+ mata: `Xm'=(J(`poly_nr', `deriv',0), `Xm')
1593
+ if (`nwvar'>0) {
1594
+ if (`deriv'==0) mata: `Xm'=(`Xm', J(`poly_nr',1,1)#st_matrix("`wval'"))
1595
+ else mata: `Xm'=(`Xm', J(`poly_nr',`nwvar',0))
1596
+ }
1597
+
1598
+ if ("`transform'"=="T") {
1599
+ if (`deriv'==0) {
1600
+ mata:`plotmatby'[|1,`poly_start'+3 \ `poly_nr',`poly_start'+3|]=logistic(`Xm'*st_matrix("`poly_b'")')
1601
+ }
1602
+ else if (`deriv'==1) {
1603
+ forval i=0/`polyreg' {
1604
+ mata: `Xm0'=(`Xm0', `plotmatby'[|1,`poly_start' \ `poly_nr',`poly_start'|]:^`i')
1605
+ }
1606
+ if (`nwvar'>0) mata: `Xm0'=(`Xm0', J(`poly_nr',1,1)#st_matrix("`wval'"))
1607
+ mata:`plotmatby'[|1,`poly_start'+3 \ `poly_nr',`poly_start'+3|]=logisticden(`Xm0'*st_matrix("`poly_b'")'):* ///
1608
+ (`Xm'*st_matrix("`poly_b'")')
1609
+ }
1610
+ }
1611
+ else {
1612
+ mata:`plotmatby'[|1,`poly_start'+3 \ `poly_nr',`poly_start'+3|]=`Xm'*st_matrix("`poly_b'")'
1613
+ }
1614
+
1615
+ mata: mata drop `Xm' `Xm0'
1616
+
1617
+ local plotnum=`plotnum'+1
1618
+ local col: word `counter_by' of `bycolors'
1619
+ local lty: word `counter_by' of `bylpatterns'
1620
+ local plotcond ""
1621
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1622
+ local plotcond if
1623
+ if ("`plotxrange'"!="") {
1624
+ local plotcond `plotcond' poly_x>=`min_xr'
1625
+ if ("`max_xr'"!="") local plotcond `plotcond' &poly_x<=`max_xr'
1626
+ }
1627
+ if ("`plotyrange'"!="") {
1628
+ if ("`plotxrange'"=="") local plotcond `plotcond' poly_fit>=`min_yr'
1629
+ else local plotcond `plotcond' &poly_fit>=`min_yr'
1630
+ if ("`max_yr'"!="") local plotcond `plotcond' &poly_fit<=`max_yr'
1631
+ }
1632
+ }
1633
+
1634
+ local plotcmdby `plotcmdby' (line poly_fit poly_x ///
1635
+ `plotcond' in `poly_first'/`poly_last', ///
1636
+ sort lcolor(`col') lpattern(`lty') `polyregplotopt')
1637
+
1638
+ * add CI for global poly?
1639
+ if (`polyregcingrid'!=0) {
1640
+ local polyci_first=`byfirst'
1641
+ local polyci_last=`byfirst'-1+`polyci_nr'
1642
+
1643
+ mata: `plotmatby'[|1,`polyci_start' \ `polyci_nr',`polyci_start'+2|]=binsreg_grids("`kmat'", `polyregcingrid')
1644
+
1645
+ mata: `Xm'=J(`polyci_nr',0,.); `Xm0'=J(`polyci_nr',0,.)
1646
+ forval i=`deriv'/`polyreg' {
1647
+ mata:`Xm'=(`Xm', ///
1648
+ `plotmatby'[|1,`polyci_start' \ `polyci_nr',`polyci_start'|]:^(`i'-`deriv')* ///
1649
+ factorial(`i')/factorial(`i'-`deriv'))
1650
+ }
1651
+ mata: `Xm'=(J(`polyci_nr', `deriv',0), `Xm')
1652
+ if (`nwvar'>0) {
1653
+ if (`deriv'==0) mata: `Xm'=(`Xm', J(`polyci_nr',1,1)#st_matrix("`wval'"))
1654
+ else mata: `Xm'=(`Xm', J(`polyci_nr',`nwvar',0))
1655
+ }
1656
+
1657
+ if ("`transform'"=="T") {
1658
+ if (`deriv'==0) {
1659
+ mata: `mata_fit'=logistic(`Xm'*st_matrix("`poly_b'")')
1660
+ mata: `mata_se'=logisticden(`Xm'*st_matrix("`poly_b'")'):* ///
1661
+ sqrt(rowsum((`Xm'*st_matrix("`poly_V'")):*`Xm'))
1662
+ }
1663
+ else if (`deriv'==1) {
1664
+ forval i=0/`polyreg' {
1665
+ mata: `Xm0'=(`Xm0', `plotmatby'[|1,`polyci_start' \ `polyci_nr',`polyci_start'|]:^`i')
1666
+ }
1667
+ if (`nwvar'>0) mata: `Xm0'=(`Xm0', J(`polyci_nr',1,1)#st_matrix("`wval'"))
1668
+ mata:`mata_fit'=logisticden(`Xm0'*st_matrix("`poly_b'")'):* ///
1669
+ (`Xm'*st_matrix("`poly_b'")')
1670
+
1671
+ tempname tempobj
1672
+ mata: `tempobj'=`Xm0'*st_matrix("`poly_b'")'; ///
1673
+ `tempobj'=logisticden(`tempobj'):*(1:-2*logistic(`tempobj')):*(`Xm'*st_matrix("`poly_b'")'):*`Xm0' + ///
1674
+ logisticden(`tempobj'):*`Xm'; ///
1675
+ `mata_se'=sqrt(rowsum((`tempobj'*st_matrix("`poly_V'")):*`tempobj'))
1676
+ mata: mata drop `tempobj'
1677
+ }
1678
+ }
1679
+ else {
1680
+ mata: `mata_fit'=`Xm'*st_matrix("`poly_b'")'; ///
1681
+ `mata_se'=sqrt(rowsum((`Xm'*st_matrix("`poly_V'")):*`Xm'))
1682
+ }
1683
+
1684
+ mata:`plotmatby'[|1,`polyci_start'+3 \ `polyci_nr',`polyci_start'+3|]=`mata_fit'-`mata_se'*invnormal(`alpha'); ///
1685
+ `plotmatby'[|1,`polyci_start'+4 \ `polyci_nr',`polyci_start'+4|]=`mata_fit'+`mata_se'*invnormal(`alpha'); ///
1686
+ `plotmatby'[selectindex(`plotmatby'[,`=`polyci_start'+1']:==1),(`=`polyci_start'+3',`=`polyci_start'+4')]=J(`=`nbins'-1',2,.)
1687
+
1688
+ mata: mata drop `Xm' `Xm0' `mata_fit' `mata_se'
1689
+
1690
+ * poly ci
1691
+ local plotnum=`plotnum'+1
1692
+ local plotcond ""
1693
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1694
+ local plotcond if
1695
+ if ("`plotxrange'"!="") {
1696
+ local plotcond `plotcond' polyCI_x>=`min_xr'
1697
+ if ("`max_xr'"!="") local plotcond `plotcond' &polyCI_x<=`max_xr'
1698
+ }
1699
+ if ("`plotyrange'"!="") {
1700
+ if ("`plotxrange'"=="") local plotcond `plotcond' polyCI_l>=`min_yr'
1701
+ else local plotcond `plotcond' &polyCI_l>=`min_yr'
1702
+ if ("`max_yr'"!="") local plotcond `plotcond' &polyCI_r<=`max_yr'
1703
+ }
1704
+ }
1705
+
1706
+ local plotcmdby `plotcmdby' (rcap polyCI_l polyCI_r polyCI_x ///
1707
+ `plotcond' in `polyci_first'/`polyci_last', ///
1708
+ sort lcolor(`col') lpattern(`lty') `ciplotopt')
1709
+ }
1710
+ }
1711
+
1712
+
1713
+ **********************************
1714
+ ******* Confidence Interval ******
1715
+ **********************************
1716
+ if ("`ciON'"=="T") {
1717
+ local ci_first=`byfirst'
1718
+ local ci_last=`byfirst'-1+`ci_nr'
1719
+
1720
+ * fitting
1721
+ tempname ci_b ci_V
1722
+ capture confirm matrix `line_b' `line_V'
1723
+ if ("`ci_p'"=="`line_p'"& "`ci_s'"=="`line_s'" & _rc==0) {
1724
+ matrix `ci_b'=`line_b'
1725
+ matrix `ci_V'=`line_V'
1726
+ }
1727
+ else {
1728
+ capture confirm matrix `dots_b' `dots_V'
1729
+ if ("`ci_p'"=="`dots_p'"& "`ci_s'"=="`dots_s'" & _rc==0) {
1730
+ matrix `ci_b'=`dots_b'
1731
+ matrix `ci_V'=`dots_V'
1732
+ }
1733
+ }
1734
+
1735
+ capture confirm matrix `ci_b' `ci_V' `xmean'
1736
+ if (_rc!=0) {
1737
+ binslogit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1738
+ p(`ci_p') s(`ci_s') type(ci) `vce' ///
1739
+ xcat(`xcat') kmat(`kmat') dotsmean(`cingrid_mean') ///
1740
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1741
+ `sorted' `usegtools' logitopt(`logitopt')
1742
+
1743
+ mat `ci_b'=e(bmat)
1744
+ mat `ci_V'=e(Vmat)
1745
+ mat `xmean'=e(xmat)
1746
+ }
1747
+
1748
+ * prediction
1749
+ if (`cingrid_mean'==0) {
1750
+ mata: `plotmatby'[|1,`ci_start' \ `ci_nr',`ci_end'|] = ///
1751
+ binslogit_plotmat("`ci_b'", "`ci_V'", ///
1752
+ `=invnormal(`alpha')', "`kmat'", ///
1753
+ `nbins', `ci_p', `ci_s', `deriv', "ci", ///
1754
+ `cingrid', "`wval'", `nwvar', "`transform'", "`asyvar'")
1755
+ }
1756
+ else {
1757
+ mata: `plotmatby'[|1,`ci_start' \ `ci_nr',`ci_end'|] = ///
1758
+ binslogit_plotmat("`ci_b'", "`ci_V'", ///
1759
+ `=invnormal(`alpha')', "`kmat'", ///
1760
+ `nbins', `ci_p', `ci_s', `deriv', "ci", ///
1761
+ `cingrid', "`wval'", `nwvar', ///
1762
+ "`transform'", "`asyvar'", "`xmean'")
1763
+ }
1764
+
1765
+ * ci
1766
+ local plotnum=`plotnum'+1
1767
+ local col: word `counter_by' of `bycolors'
1768
+ local lty: word `counter_by' of `bylpatterns'
1769
+ local plotcond ""
1770
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1771
+ local plotcond if
1772
+ if ("`plotxrange'"!="") {
1773
+ local plotcond `plotcond' CI_x>=`min_xr'
1774
+ if ("`max_xr'"!="") local plotcond `plotcond' &CI_x<=`max_xr'
1775
+ }
1776
+ if ("`plotyrange'"!="") {
1777
+ if ("`plotxrange'"=="") local plotcond `plotcond' CI_l>=`min_yr'
1778
+ else local plotcond `plotcond' &CI_l>=`min_yr'
1779
+ if ("`max_yr'"!="") local plotcond `plotcond' &CI_r<=`max_yr'
1780
+ }
1781
+ }
1782
+
1783
+ local plotcmdby `plotcmdby' (rcap CI_l CI_r CI_x ///
1784
+ `plotcond' in `ci_first'/`ci_last', ///
1785
+ sort lcolor(`col') lpattern(`lty') `ciplotopt')
1786
+
1787
+ }
1788
+
1789
+ *******************************
1790
+ ***** Confidence Band *********
1791
+ *******************************
1792
+ tempname cval
1793
+ scalar `cval'=.
1794
+ if ("`cbON'"=="T") {
1795
+ if (`nsims'<2000|`simsgrid'<50) {
1796
+ di as text "Note: A larger number random draws/evaluation points is recommended to obtain the final results."
1797
+ }
1798
+ * Prepare grid for plotting
1799
+ local cb_first=`byfirst'
1800
+ local cb_last=`byfirst'-1+`cb_nr'
1801
+
1802
+ * fitting
1803
+ tempname cb_b cb_V
1804
+ capture confirm matrix `ci_b' `ci_V'
1805
+ if ("`cb_p'"=="`ci_p'"& "`cb_s'"=="`ci_s'" & _rc==0) {
1806
+ matrix `cb_b'=`ci_b'
1807
+ matrix `cb_V'=`ci_V'
1808
+ }
1809
+ else {
1810
+ capture confirm matrix `line_b' `line_V'
1811
+ if ("`cb_p'"=="`line_p'"& "`cb_s'"=="`line_s'" & _rc==0) {
1812
+ matrix `cb_b'=`line_b'
1813
+ matrix `cb_V'=`line_V'
1814
+ }
1815
+ else {
1816
+ capture confirm matrix `dots_b' `dots_V'
1817
+ if ("`cb_p'"=="`dots_p'"& "`cb_s'"=="`dots_s'" & _rc==0) {
1818
+ matrix `cb_b'=`dots_b'
1819
+ matrix `cb_V'=`dots_V'
1820
+ }
1821
+ else {
1822
+ binslogit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1823
+ p(`cb_p') s(`cb_s') type(cb) `vce' ///
1824
+ xcat(`xcat') kmat(`kmat') dotsmean(0) ///
1825
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1826
+ `sorted' `usegtools' logitopt(`logitopt')
1827
+ mat `cb_b'=e(bmat)
1828
+ mat `cb_V'=e(Vmat)
1829
+ }
1830
+ }
1831
+ }
1832
+
1833
+ * Compute critical values
1834
+ * Prepare grid for simulation
1835
+ local uni_last=`simsngrid'*`nbins'+`nbins'-1
1836
+ local nseries=(`cb_p'-`cb_s'+1)*(`nbins'-1)+`cb_p'+1
1837
+
1838
+ tempname cb_basis
1839
+ mata: `cb_basis'=binsreg_grids("`kmat'", `simsngrid'); ///
1840
+ `cb_basis'=binsreg_spdes(`cb_basis'[,1], "`kmat'", `cb_basis'[,3], `cb_p', `deriv', `cb_s'); ///
1841
+ `Xm'=binsreg_pred(`cb_basis', st_matrix("`cb_b'")[|1 \ `nseries'|]', ///
1842
+ st_matrix("`cb_V'")[|1,1 \ `nseries',`nseries'|], "all"); ///
1843
+ binsreg_pval(`cb_basis', `Xm'[,2], "`cb_V'", ".", `nsims', `nseries', "two", `=`level'/100', ".", "`cval'", "inf")
1844
+ mata: mata drop `cb_basis' `Xm'
1845
+
1846
+ * prediction
1847
+ mata: `plotmatby'[|1,`cb_start' \ `cb_nr',`cb_end'|] = ///
1848
+ binslogit_plotmat("`cb_b'", "`cb_V'", ///
1849
+ `=`cval'', "`kmat'", ///
1850
+ `nbins', `cb_p', `cb_s', `deriv', ///
1851
+ "cb", `cbngrid', "`wval'", `nwvar', ///
1852
+ "`transform'", "`asyvar'")
1853
+
1854
+ * cb
1855
+ local plotnum=`plotnum'+1
1856
+ local col: word `counter_by' of `bycolors'
1857
+ local plotcond ""
1858
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1859
+ local plotcond if
1860
+ if ("`plotxrange'"!="") {
1861
+ local plotcond `plotcond' CB_x>=`min_xr'
1862
+ if ("`max_xr'"!="") local plotcond `plotcond' &CB_x<=`max_xr'
1863
+ }
1864
+ if ("`plotyrange'"!="") {
1865
+ if ("`plotxrange'"=="") local plotcond `plotcond' CB_l>=`min_yr'
1866
+ else local plotcond `plotcond' &CB_l>=`min_yr'
1867
+ if ("`max_yr'"!="") local plotcond `plotcond' &(CB_r<=`max_yr'|CB_r==.)
1868
+ }
1869
+ }
1870
+
1871
+ local plotcmdby (rarea CB_l CB_r CB_x ///
1872
+ `plotcond' in `cb_first'/`cb_last', sort cmissing(n) ///
1873
+ lcolor(none%0) fcolor(`col'%50) fintensity(50) `cbplotopt') `plotcmdby'
1874
+ }
1875
+ mat `cvallist'=(nullmat(`cvallist') \ `cval')
1876
+
1877
+ local plotcmd `plotcmd' `plotcmdby'
1878
+ mata: `plotmat'=(`plotmat' \ `plotmatby')
1879
+
1880
+ *********************************
1881
+ **** display ********************
1882
+ *********************************
1883
+ di ""
1884
+ * Plotting
1885
+ if ("`plot'"=="") {
1886
+ if (`counter_by'==1) {
1887
+ di in smcl in gr "Binscatter plot, logit model"
1888
+ di in smcl in gr "Bin selection method: `binselectmethod'"
1889
+ di in smcl in gr "Placement: `placement'"
1890
+ di in smcl in gr "Derivative: `deriv'"
1891
+ if (`"`savedata'"'!=`""') {
1892
+ di in smcl in gr `"Output file: `savedata'.dta"'
1893
+ }
1894
+ }
1895
+ di ""
1896
+ if ("`by'"!="") {
1897
+ di in smcl in gr "Group: `byvarname' = " in yellow "`byvalname'"
1898
+ }
1899
+ di in smcl in gr "{hline 30}{c TT}{hline 15}"
1900
+ di in smcl in gr "{lalign 1:# of observations}" _col(30) " {c |} " _col(32) as result %7.0f `N'
1901
+ di in smcl in gr "{lalign 1:# of distinct values}" _col(30) " {c |} " _col(32) as result %7.0f `Ndist'
1902
+ di in smcl in gr "{lalign 1:# of clusters}" _col(30) " {c |} " _col(32) as result %7.0f `Nclust'
1903
+ di in smcl in gr "{hline 30}{c +}{hline 15}"
1904
+ di in smcl in gr "{lalign 1:Bin/Degree selection:}" _col(30) " {c |} "
1905
+ if ("`selection'"=="P") {
1906
+ di in smcl in gr "{ralign 29:Degree of polynomial}" _col(30) " {c |} " _col(32) as result %7.0f `binsp'
1907
+ di in smcl in gr "{ralign 29:# of smoothness constraints}" _col(30) " {c |} " _col(32) as result %7.0f `binss'
1908
+ }
1909
+ else {
1910
+ di in smcl in gr "{ralign 29:Degree of polynomial}" _col(30) " {c |} " _col(32) as result %7.0f `dots_p'
1911
+ di in smcl in gr "{ralign 29:# of smoothness constraints}" _col(30) " {c |} " _col(32) as result %7.0f `dots_s'
1912
+ }
1913
+
1914
+ di in smcl in gr "{ralign 29:# of bins}" _col(30) " {c |} " _col(32) as result %7.0f `nbins'
1915
+ if ("`binselectmethod'"!="User-specified") {
1916
+ if ("`binsmethod'"=="ROT") {
1917
+ di in smcl in gr "{ralign 29:imse, bias^2}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_bsq_rot'[`counter_by',1]'
1918
+ di in smcl in gr "{ralign 29:imse, var.}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_var_rot'[`counter_by',1]'
1919
+ }
1920
+ else if ("`binsmethod'"=="DPI") {
1921
+ di in smcl in gr "{ralign 29:imse, bias^2}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_bsq_dpi'[`counter_by',1]'
1922
+ di in smcl in gr "{ralign 29:imse, var.}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_var_dpi'[`counter_by',1]'
1923
+ }
1924
+ }
1925
+ di in smcl in gr "{hline 30}{c BT}{hline 15}"
1926
+ di ""
1927
+ di in smcl in gr "{hline 9}{c TT}{hline 30}"
1928
+ di in smcl _col(10) "{c |}" in gr _col(17) "p" _col(25) "s" _col(33) "df"
1929
+ di in smcl in gr "{hline 9}{c +}{hline 30}"
1930
+ if (`dotsntot'!=0) {
1931
+ local dots_df=(`dots_p'-`dots_s'+1)*(`nbins'-1)+`dots_p'+1
1932
+ di in smcl in gr "{lalign 1: dots}" _col(10) "{c |}" in gr _col(17) "`dots_p'" _col(25) "`dots_s'" _col(33) "`dots_df'"
1933
+ }
1934
+ if ("`lineON'"=="T") {
1935
+ local line_df=(`line_p'-`line_s'+1)*(`nbins'-1)+`line_p'+1
1936
+ di in smcl in gr "{lalign 1: line}" _col(10) "{c |}" in gr _col(17) "`line_p'" _col(25) "`line_s'" _col(33) "`line_df'"
1937
+ }
1938
+ if (`cintot'!=0) {
1939
+ local ci_df=(`ci_p'-`ci_s'+1)*(`nbins'-1)+`ci_p'+1
1940
+ di in smcl in gr "{lalign 1: CI}" _col(10) "{c |}" in gr _col(17) "`ci_p'" _col(25) "`ci_s'" _col(33) "`ci_df'"
1941
+ }
1942
+ if ("`cbON'"=="T") {
1943
+ local cb_df=(`cb_p'-`cb_s'+1)*(`nbins'-1)+`cb_p'+1
1944
+ di in smcl in gr "{lalign 1: CB}" _col(10) "{c |}" in gr _col(17) "`cb_p'" _col(25) "`cb_s'" _col(33) "`cb_df'"
1945
+ }
1946
+ if ("`polyON'"=="T") {
1947
+ local poly_df=`polyreg'+1
1948
+ di in smcl in gr "{lalign 1: polyreg}" _col(10) "{c |}" in gr _col(17) "`polyreg'" _col(25) "NA" _col(33) "`poly_df'"
1949
+ }
1950
+ di in smcl in gr "{hline 9}{c BT}{hline 30}"
1951
+ }
1952
+
1953
+
1954
+ mata: mata drop `plotmatby'
1955
+ local ++counter_by
1956
+ }
1957
+ mata: mata drop `xsub' `ysub' `binedges'
1958
+ if (`bynum'>1) mata: mata drop `byindex'
1959
+ capture mata: mata drop `xcatsub'
1960
+ ****************** END loop ****************************************
1961
+ ********************************************************************
1962
+
1963
+
1964
+
1965
+ *******************************************
1966
+ *************** Plotting ******************
1967
+ *******************************************
1968
+ clear
1969
+ if ("`plotcmd'"!="") {
1970
+ * put data back to STATA
1971
+ mata: st_local("nr", strofreal(rows(`plotmat')))
1972
+ qui set obs `nr'
1973
+
1974
+ * MAKE SURE the orderings match
1975
+ qui gen group=. in 1
1976
+ if (`dotsntot'!=0) {
1977
+ qui gen dots_x=. in 1
1978
+ qui gen dots_isknot=. in 1
1979
+ qui gen dots_binid=. in 1
1980
+ qui gen dots_fit=. in 1
1981
+ }
1982
+ if (`linengrid'!=0&"`fullfewobs'"=="") {
1983
+ qui gen line_x=. in 1
1984
+ qui gen line_isknot=. in 1
1985
+ qui gen line_binid=. in 1
1986
+ qui gen line_fit=. in 1
1987
+ }
1988
+ if (`polyregngrid'!=0) {
1989
+ qui gen poly_x=. in 1
1990
+ qui gen poly_isknot=. in 1
1991
+ qui gen poly_binid=. in 1
1992
+ qui gen poly_fit=. in 1
1993
+ if (`polyregcingrid'!=0) {
1994
+ qui gen polyCI_x=. in 1
1995
+ qui gen polyCI_isknot=. in 1
1996
+ qui gen polyCI_binid=. in 1
1997
+ qui gen polyCI_l=. in 1
1998
+ qui gen polyCI_r=. in 1
1999
+ }
2000
+ }
2001
+ if (`cintot'!=0) {
2002
+ qui gen CI_x=. in 1
2003
+ qui gen CI_isknot=. in 1
2004
+ qui gen CI_binid=. in 1
2005
+ qui gen CI_l=. in 1
2006
+ qui gen CI_r=. in 1
2007
+ }
2008
+ if (`cbngrid'!=0&"`fullfewobs'"=="") {
2009
+ qui gen CB_x=. in 1
2010
+ qui gen CB_isknot=. in 1
2011
+ qui gen CB_binid=. in 1
2012
+ qui gen CB_l=. in 1
2013
+ qui gen CB_r=. in 1
2014
+ }
2015
+
2016
+ mata: st_store(.,.,`plotmat')
2017
+
2018
+ * Legend
2019
+ local plot_legend legend(order(
2020
+ if ("`by'"!=""&`dotsntot'!=0) {
2021
+ forval i=1/`bynum' {
2022
+ local byvalname: word `i' of `byvalnamelist'
2023
+ local plot_legend `plot_legend' `: word `i' of `legendnum'' "`byvarname'=`byvalname'"
2024
+ }
2025
+ local plot_legend `plot_legend' ))
2026
+ }
2027
+ else {
2028
+ local plot_legend legend(off)
2029
+ }
2030
+
2031
+ * Plot it
2032
+ local graphcmd twoway `plotcmd', xtitle(`x_varname') ytitle(`y_varname') xscale(range(`xsc')) `plot_legend' `options'
2033
+ `graphcmd'
2034
+ }
2035
+ mata: mata drop `plotmat' `xvec' `yvec' `byvec' `cluvec'
2036
+
2037
+
2038
+ * Save graph data ?
2039
+ * In the normal case
2040
+ if (`"`savedata'"'!=`""'&`"`plotcmd'"'!=`""') {
2041
+ * Add labels
2042
+ if ("`by'"!="") {
2043
+ if ("`bystring'"=="T") {
2044
+ label val group `bylabel'
2045
+ decode group, gen(`byvarname')
2046
+ }
2047
+ else {
2048
+ qui gen `byvarname'=group
2049
+ if ("`bylabel'"!="") label val `byvarname' `bylabel'
2050
+ }
2051
+ label var `byvarname' "Group"
2052
+ qui drop group
2053
+ order `byvarname'
2054
+ }
2055
+ else qui drop group
2056
+
2057
+ capture confirm variable dots_x dots_binid dots_isknot dots_fit
2058
+ if (_rc==0) {
2059
+ label var dots_x "Dots: grid"
2060
+ label var dots_binid "Dots: indicator of bins"
2061
+ label var dots_isknot "Dots: indicator of inner knot"
2062
+ label var dots_fit "Dots: fitted values"
2063
+ }
2064
+ capture confirm variable line_x line_binid line_isknot line_fit
2065
+ if (_rc==0) {
2066
+ label var line_x "Line: grid"
2067
+ label var line_binid "Line: indicator of bins"
2068
+ label var line_isknot "Line: indicator of inner knot"
2069
+ label var line_fit "Line: fitted values"
2070
+ }
2071
+ capture confirm variable poly_x poly_binid poly_isknot poly_fit
2072
+ if (_rc==0) {
2073
+ label var poly_x "Poly: grid"
2074
+ label var poly_binid "Poly: indicator of bins"
2075
+ label var poly_isknot "Poly: indicator of inner knot"
2076
+ label var poly_fit "Poly: fitted values"
2077
+ }
2078
+ capture confirm variable polyCI_x polyCI_binid polyCI_isknot polyCI_l polyCI_r
2079
+ if (_rc==0) {
2080
+ label var polyCI_x "Poly confidence interval: grid"
2081
+ label var polyCI_binid "Poly confidence interval: indicator of bins"
2082
+ label var polyCI_isknot "Poly confidence interval: indicator of inner knot"
2083
+ label var polyCI_l "Poly confidence interval: left boundary"
2084
+ label var polyCI_r "Poly confidence interval: right boundary"
2085
+ }
2086
+ capture confirm variable CI_x CI_binid CI_isknot CI_l CI_r
2087
+ if (_rc==0) {
2088
+ label var CI_x "Confidence interval: grid"
2089
+ label var CI_binid "Confidence interval: indicator of bins"
2090
+ label var CI_isknot "Confidence interval: indicator of inner knot"
2091
+ label var CI_l "Confidence interval: left boundary"
2092
+ label var CI_r "Confidence interval: right boundary"
2093
+ }
2094
+ capture confirm variable CB_x CB_binid CB_isknot CB_l CB_r
2095
+ if (_rc==0) {
2096
+ label var CB_x "Confidence band: grid"
2097
+ label var CB_binid "Confidence band: indicator of bins"
2098
+ label var CB_isknot "Confidence band: indicator of inner knot"
2099
+ label var CB_l "Confidence band: left boundary"
2100
+ label var CB_r "Confidence band: right boundary"
2101
+ }
2102
+ qui save `"`savedata'"', `replace'
2103
+ }
2104
+ ***************************************************************************
2105
+
2106
+ *********************************
2107
+ ********** Return ***************
2108
+ *********************************
2109
+ ereturn clear
2110
+ * # of observations
2111
+ ereturn scalar N=`Ntotal'
2112
+ * Options
2113
+ ereturn scalar level=`level'
2114
+ ereturn scalar dots_p=`dots_p'
2115
+ ereturn scalar dots_s=`dots_s'
2116
+ ereturn scalar line_p=`line_p'
2117
+ ereturn scalar line_s=`line_s'
2118
+ ereturn scalar ci_p=`ci_p'
2119
+ ereturn scalar ci_s=`ci_s'
2120
+ ereturn scalar cb_p=`cb_p'
2121
+ ereturn scalar cb_s=`cb_s'
2122
+ * by group:
2123
+ *ereturn matrix knot=`kmat'
2124
+ ereturn matrix cval_by=`cvallist'
2125
+ ereturn matrix nbins_by=`nbinslist'
2126
+ ereturn matrix Nclust_by=`Nclustlist'
2127
+ ereturn matrix Ndist_by=`Ndistlist'
2128
+ ereturn matrix N_by=`Nlist'
2129
+
2130
+ ereturn matrix imse_var_rot=`mat_imse_var_rot'
2131
+ ereturn matrix imse_bsq_rot=`mat_imse_bsq_rot'
2132
+ ereturn matrix imse_var_dpi=`mat_imse_var_dpi'
2133
+ ereturn matrix imse_bsq_dpi=`mat_imse_bsq_dpi'
2134
+ end
2135
+
2136
+ * Helper commands
2137
+ * Estimation
2138
+ program define binslogit_fit, eclass
2139
+ version 13
2140
+ syntax varlist(min=2 numeric ts fv) [if] [in] [fw aw pw] [, deriv(integer 0) ///
2141
+ p(integer 0) s(integer 0) type(string) vce(passthru) ///
2142
+ xcat(varname numeric) kmat(name) dotsmean(integer 0) /// /* xmean: report x-mean? */
2143
+ xname(name) yname(name) catname(name) edge(name) ///
2144
+ usereg sorted usegtools logitopt(string asis)] /* usereg: force the command to use reg; sored: sorted data? */
2145
+
2146
+ preserve
2147
+ marksample touse
2148
+ qui keep if `touse'
2149
+
2150
+ if ("`weight'"!="") local wt [`weight'`exp']
2151
+
2152
+ tokenize `varlist'
2153
+ local y_var `1'
2154
+ local x_var `2'
2155
+ macro shift 2
2156
+ local w_var "`*'"
2157
+ local nbins=rowsof(`kmat')-1
2158
+
2159
+ tempname matxmean temp_b temp_V
2160
+ mat `matxmean'=.
2161
+ mat `temp_b'=.
2162
+ mat `temp_V'=.
2163
+
2164
+ if (`dotsmean'!=0) {
2165
+ if ("`sorted'"==""|"`weight'"!=""|"`usegtools'"!="") {
2166
+ if ("`usegtools'"=="") {
2167
+ tempfile tmpfile
2168
+ qui save `tmpfile', replace
2169
+
2170
+ collapse (mean) `x_var' `wt', by(`xcat') fast
2171
+ mkmat `xcat' `x_var', matrix(`matxmean')
2172
+
2173
+ use `tmpfile', clear
2174
+ }
2175
+ else {
2176
+ tempname obj
2177
+ qui gstats tabstat `x_var' `wt', stats(mean) by(`xcat') matasave("`obj'")
2178
+ mata: st_matrix("`matxmean'", (`obj'.getnum(.,1), `obj'.getOutputVar("`x_var'")))
2179
+ mata: mata drop `obj'
2180
+ }
2181
+ }
2182
+ else {
2183
+ tempname output
2184
+ mata: `output'=binsreg_stat(`xname', `catname', `nbins', `edge', "mean", -1); ///
2185
+ st_matrix("`matxmean'", `output')
2186
+ mata: mata drop `output'
2187
+ }
2188
+ }
2189
+
2190
+ * Regression?
2191
+ if (`p'==0) {
2192
+ capture logit `y_var' ibn.`xcat' `w_var' `wt', nocon `vce' `logitopt'
2193
+ if (_rc==0) {
2194
+ matrix `temp_b'=e(b)
2195
+ matrix `temp_V'=e(V)
2196
+ }
2197
+ else {
2198
+ error _rc
2199
+ exit _rc
2200
+ }
2201
+ }
2202
+ else {
2203
+ local nseries=(`p'-`s'+1)*(`nbins'-1)+`p'+1
2204
+ local series ""
2205
+ forvalues i=1/`nseries' {
2206
+ tempvar sp`i'
2207
+ local series `series' `sp`i''
2208
+ qui gen `sp`i''=. in 1
2209
+ }
2210
+
2211
+ mata: binsreg_st_spdes(`xname', "`series'", "`kmat'", `catname', `p', 0, `s')
2212
+
2213
+ capture logit `y_var' `series' `w_var' `wt', nocon `vce' `logitopt'
2214
+ * store results
2215
+ if (_rc==0) {
2216
+ matrix `temp_b'=e(b)
2217
+ matrix `temp_V'=e(V)
2218
+ mata: binsreg_checkdrop("`temp_b'", "`temp_V'", `nseries')
2219
+ }
2220
+ else {
2221
+ error _rc
2222
+ exit _rc
2223
+ }
2224
+ }
2225
+
2226
+
2227
+ ereturn clear
2228
+ ereturn matrix bmat=`temp_b'
2229
+ ereturn matrix Vmat=`temp_V'
2230
+ ereturn matrix xmat=`matxmean' /* xcat, xbar */
2231
+ end
2232
+
2233
+ mata:
2234
+
2235
+ // Prediction for plotting
2236
+ real matrix binslogit_plotmat(string scalar eb, string scalar eV, real scalar cval, ///
2237
+ string scalar knotname, real scalar J, ///
2238
+ real scalar p, real scalar s, real scalar deriv, ///
2239
+ string scalar type, real scalar ngrid, string scalar muwmat, ///
2240
+ real scalar nw, string scalar transform, string scalar avar, | string scalar muxmat)
2241
+ {
2242
+ real matrix coef, bmat, rmat, vmat, knot, xmean, wval, eval, out, fit, fit0, se, semat, Xm, Xm0, result
2243
+ real scalar nseries
2244
+
2245
+ nseries=(p-s+1)*(J-1)+p+1
2246
+ coef=st_matrix(eb)'
2247
+ bmat=coef[|1\nseries|]
2248
+ if (nw>0) rmat=coef[|(nseries+1)\rows(coef)|]
2249
+
2250
+ if (type=="ci"|type=="cb") {
2251
+ vfull=st_matrix(eV)
2252
+ vmat=vfull[|1,1\nseries,nseries|]
2253
+ }
2254
+
2255
+ // Prepare evaluation points
2256
+ eval=J(0,3,.)
2257
+ if (args()==15) {
2258
+ xmean=st_matrix(muxmat)
2259
+ eval=(eval \ (xmean[,2], J(J, 1, 0), xmean[,1]))
2260
+ }
2261
+ if (ngrid!=0) {
2262
+ eval=(eval \ binsreg_grids(knotname, ngrid))
2263
+ }
2264
+
2265
+ // adjust w variables
2266
+ if (nw>0) {
2267
+ wvec=st_matrix(muwmat)
2268
+ wval=wvec*rmat
2269
+ }
2270
+ else wval=0
2271
+
2272
+ fit=J(0,1,.)
2273
+ se=J(0,1,.)
2274
+ if (p==0) {
2275
+ if (args()==15) fit=(fit \ bmat)
2276
+ if (ngrid!=0) {
2277
+ fit=(fit \ (bmat#(J(ngrid,1,1)\.)))
2278
+ fit=fit[|1 \ (rows(fit)-1)|]
2279
+ }
2280
+ if (type=="ci"|type=="cb") {
2281
+ if (avar=="on") semat=sqrt(diagonal(vmat))
2282
+ else {
2283
+ if (nw>0) {
2284
+ Xm=(I(nseries), J(nseries,1,1)#wvec)
2285
+ semat=sqrt(rowsum((Xm*vfull):*Xm))
2286
+ }
2287
+ else semat=sqrt(diagonal(vmat))
2288
+ }
2289
+ if (args()==15) se=(se \ semat)
2290
+ if (ngrid!=0) {
2291
+ se=(se \ (semat#(J(ngrid,1,1)\.)))
2292
+ se=se[|1 \ (rows(se)-1)|]
2293
+ }
2294
+ }
2295
+ if (type=="dots"|type=="line") {
2296
+ if (transform=="T") out=(eval, logistic(fit:+wval))
2297
+ else out=(eval, fit:+wval)
2298
+ }
2299
+ else {
2300
+ if (transform=="T") out=(eval, logistic(fit:+wval)-(logisticden(fit:+wval):*se)*cval, ///
2301
+ logistic(fit:+wval)+(logisticden(fit:+wval):*se)*cval)
2302
+ else out=(eval, (fit:+wval)-se*cval, (fit:+wval)+se*cval)
2303
+ }
2304
+ }
2305
+ else {
2306
+ Xm=binsreg_spdes(eval[,1], knotname, eval[,3], p, deriv, s)
2307
+ if (type=="dots"|type=="line") {
2308
+ if (transform=="T") {
2309
+ fit=binsreg_pred(Xm, bmat, ., "xb")[,1]
2310
+ if (deriv==0) {
2311
+ fit=logistic(fit:+wval)
2312
+ }
2313
+ if (deriv==1) {
2314
+ Xm0=binsreg_spdes(eval[,1], knotname, eval[,3], p, 0, s)
2315
+ fit0=binsreg_pred(Xm0, bmat, ., "xb")[,1]
2316
+ fit=logisticden(fit0:+wval):*fit
2317
+ }
2318
+ out=(eval, fit)
2319
+ }
2320
+ else {
2321
+ fit=binsreg_pred(Xm, bmat, ., "xb")[,1]
2322
+ if (deriv==0) out=(eval, fit:+wval)
2323
+ else out=(eval, fit)
2324
+ }
2325
+ }
2326
+ else {
2327
+ if (avar=="on") {
2328
+ result=binsreg_pred(Xm, bmat, vmat, "all")
2329
+ if (transform=="T") {
2330
+ Xm0=binsreg_spdes(eval[,1], knotname, eval[,3], p, 0, s)
2331
+ fit0=binsreg_pred(Xm0, bmat, ., "xb")[,1]
2332
+ result[,2]=logisticden(fit0:+wval):*result[,2]
2333
+
2334
+ if (deriv==0) {
2335
+ result[,1]=logistic(result[,1]:+wval)
2336
+ }
2337
+ else if (deriv==1) {
2338
+ result[,1]=logisticden(fit0:+wval):*result[,1]
2339
+ }
2340
+
2341
+ out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2342
+ }
2343
+ else {
2344
+ if (deriv==0) out=(eval, (result[,1]:+wval)-cval*result[,2], (result[,1]:+wval)+cval*result[,2])
2345
+ else out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2346
+ }
2347
+ }
2348
+ else {
2349
+ result=binsreg_pred(Xm, bmat, vmat, "all")
2350
+ if (transform=="T") {
2351
+ if (deriv==0) {
2352
+ if (nw>0) Xm=(Xm, J(rows(Xm),1,1)#wvec)
2353
+ result[,2]=logisticden(result[,1]:+wval):*sqrt(rowsum((Xm*vfull):*Xm))
2354
+ result[,1]=logistic(result[,1]:+wval)
2355
+ }
2356
+ if (deriv==1) {
2357
+ Xm0=binsreg_spdes(eval[,1], knotname, eval[,3], p, 0, s)
2358
+ if (nw>0) {
2359
+ Xm0=(Xm0, J(rows(Xm0),1,1)#wvec)
2360
+ Xm=(Xm, J(rows(Xm),nw,0))
2361
+ }
2362
+ fit0=binsreg_pred(Xm0, coef, ., "xb")[,1]
2363
+ Xm=logisticden(fit0):*(1:-2*logistic(fit0)):*result[,1]:*Xm0 + ///
2364
+ logisticden(fit0):*Xm
2365
+ result[,2]=sqrt(rowsum((Xm*vfull):*Xm))
2366
+ result[,1]=logisticden(fit0):*result[,1]
2367
+ }
2368
+ out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2369
+ }
2370
+ else {
2371
+ if (nw>0) {
2372
+ if (deriv==0) Xm=(Xm, J(rows(Xm),1,1)#wvec)
2373
+ else Xm=(Xm, J(rows(Xm),nw,0))
2374
+ }
2375
+ result=binsreg_pred(Xm, coef, vfull, "all")
2376
+ out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2377
+ }
2378
+ }
2379
+ }
2380
+ }
2381
+
2382
+ if (type=="dots"|(type=="line"&(s==0|s-deriv<=0))) {
2383
+ out[selectindex(out[,2]:==1),4]=J(sum(out[,2]),1,.)
2384
+ }
2385
+ if (type=="ci"|(type=="cb"&(s==0|s-deriv<=0))) {
2386
+ out[selectindex(out[,2]:==1),4..5]=J(sum(out[,2]),2,.)
2387
+ }
2388
+
2389
+ return(out)
2390
+ }
2391
+
2392
+
2393
+ end
2394
+
110/replication_package/replication/ado/plus/b/binslogit.sthlp ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {smcl}
2
+ {* *! version 1.2 09-OCT-2022}{...}
3
+ {viewerjumpto "Syntax" "binslogit##syntax"}{...}
4
+ {viewerjumpto "Description" "binslogit##description"}{...}
5
+ {viewerjumpto "Options" "binslogit##options"}{...}
6
+ {viewerjumpto "Examples" "binslogit##examples"}{...}
7
+ {viewerjumpto "Stored results" "binslogit##stored_results"}{...}
8
+ {viewerjumpto "References" "binslogit##references"}{...}
9
+ {viewerjumpto "Authors" "binslogit##authors"}{...}
10
+ {cmd:help binslogit}
11
+ {hline}
12
+
13
+ {title:Title}
14
+
15
+ {p 4 8}{hi:binslogit} {hline 2} Data-Driven Binscatter Logit Estimation with Robust Inference Procedures and Plots.{p_end}
16
+
17
+
18
+ {marker syntax}{...}
19
+ {title:Syntax}
20
+
21
+ {p 4 14} {cmdab:binslogit} {depvar} {it:indvar} [{it:othercovs}] {ifin} {weight} [ {cmd:,} {opt deriv(v)} {opt at(position)} {opt nolink}{p_end}
22
+ {p 14 14} {opt dots(dotsopt)} {opt dotsgrid(dotsgridoption)} {opt dotsplotopt(dotsoption)}{p_end}
23
+ {p 14 14} {opt line(lineopt)} {opt linegrid(#)} {opt lineplotopt(lineoption)}{p_end}
24
+ {p 14 14} {opt ci(ciopt)} {opt cigrid(cigridoption)} {opt ciplotopt(rcapoption)}{p_end}
25
+ {p 14 14} {opt cb(cbopt)} {opt cbgrid(#)} {opt cbplotopt(rareaoption)}{p_end}
26
+ {p 14 14} {opt polyreg(p)} {opt polyreggrid(#)} {opt polyregcigrid(#)} {opt polyregplotopt(lineoption)}{p_end}
27
+ {p 14 14} {opth by(varname)} {cmd:bycolors(}{it:{help colorstyle}list}{cmd:)} {cmd:bysymbols(}{it:{help symbolstyle}list}{cmd:)} {cmd:bylpatterns(}{it:{help linepatternstyle}list}{cmd:)}{p_end}
28
+ {p 14 14} {opt nbins(nbinsopt)} {opt binspos(position)} {opt binsmethod(method)} {opt nbinsrot(#)} {opt samebinsby} {opt randcut(#)}{p_end}
29
+ {p 14 14} {cmd:pselect(}{it:{help numlist}}{cmd:)} {cmd:sselect(}{it:{help numlist}}{cmd:)}{p_end}
30
+ {p 14 14} {opt nsims(#)} {opt simsgrid(#)} {opt simsseed(seed)}{p_end}
31
+ {p 14 14} {opt dfcheck(n1 n2)} {opt masspoints(masspointsoption)}{p_end}
32
+ {p 14 14} {cmd:vce(}{it:{help vcetype}}{cmd:)} {opt asyvar(on/off)}{p_end}
33
+ {p 14 14} {opt level(level)} {opt logitopt(logit_option)} {opt usegtools(on/off)} {opt noplot} {opt savedata(filename)} {opt replace}{p_end}
34
+ {p 14 14} {opt plotxrange(min max)} {opt plotyrange(min max)} {it:{help twoway_options}} ]{p_end}
35
+
36
+ {p 4 8} where {depvar} is the dependent variable, {it:indvar} is the independent variable for binning, and {it:othercovs} are other covariates to be controlled for.{p_end}
37
+
38
+ {p 4 8} The degree of the piecewise polynomial p, the number of smoothness constraints s, and the derivative order v are integers
39
+ satisfying 0 <= s,v <= p, which can take different values in each case.{p_end}
40
+
41
+ {p 4 8} {opt fweight}s and {opt pweight}s are allowed; see {help weight}.{p_end}
42
+
43
+ {marker description}{...}
44
+ {title:Description}
45
+
46
+ {p 4 8} {cmd:binslogit} implements binscatter logit estimation with robust inference procedures and plots, following the results in
47
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Binscatter.pdf":Cattaneo, Crump, Farrell and Feng (2022a)}.
48
+ Binscatter provides a flexible way of describing the mean relationship between two variables, after possibly adjusting for other covariates, based on partitioning/binning of the independent variable of interest.
49
+ The main purpose of this command is to generate binned scatter plots with curve estimation with robust pointwise confidence intervals and uniform confidence band.
50
+ If the binning scheme is not set by the user, the companion command {help binsregselect:binsregselect} is used to implement binscatter
51
+ in a data-driven way.
52
+ Hypothesis testing for parametric specifications of and shape restrictions on the regression function can be conducted via the
53
+ companion command {help binstest:binstest}. Hypothesis testing for pairwise group comparisons can be conducted via the
54
+ companion command {help binspwc: binspwc}. Binscatter estimation based on the least squares method can be conducted via the command {help binsreg: binsreg}.
55
+ {p_end}
56
+
57
+ {p 4 8} A detailed introduction to this command is given in
58
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Stata.pdf":Cattaneo, Crump, Farrell and Feng (2022b)}.
59
+ Companion R and Python packages with the same capabilities are available (see website below).
60
+ {p_end}
61
+
62
+ {p 4 8} Companion commands: {help binstest:binstest} for hypothesis testing of parametric specifications and shape restrictions,
63
+ {help binspwc:binspwc} for hypothesis testing for pairwise group comparisons,
64
+ and {help binsregselect:binsregselect} for data-driven binning selection.
65
+ {p_end}
66
+
67
+ {p 4 8} Related Stata, R and Python packages are available in the following website:{p_end}
68
+
69
+ {p 8 8} {browse "https://nppackages.github.io/":https://nppackages.github.io/}{p_end}
70
+
71
+
72
+ {marker options}{...}
73
+ {title:Options}
74
+
75
+ {dlgtab:Estimand}
76
+
77
+ {p 4 8} {opt deriv(v)} specifies the derivative order of the regression function for estimation and plotting.
78
+ The default is {cmd:deriv(0)}, which corresponds to the function itself.
79
+ {p_end}
80
+
81
+ {p 4 8} {opt at(position)} specifies the values of {it:othercovs} at which the estimated function is evaluated for plotting.
82
+ The default is {cmd:at(mean)}, which corresponds to the mean of {it:othercovs}. Other options are: {cmd:at(median)} for the median of {it:othercovs},
83
+ {cmd:at(0)} for zeros, and {cmd:at(filename)} for particular values of {it:othercovs} saved in another file.
84
+ {p_end}
85
+
86
+ {p 4 8} Note: When {cmd:at(mean)} or {cmd:at(median)} is specified, all factor variables in {it:othercovs} (if specified) are excluded from the evaluation (set as zero).
87
+ {p_end}
88
+
89
+ {p 4 8}{opt nolink} specifies that the function within the inverse link (logistic) function be reported instead of the conditional probability function.
90
+ {p_end}
91
+
92
+ {dlgtab:Dots}
93
+
94
+ {p 4 8} {opt dots(dotsopt)} sets the degree of polynomial and the number of smoothness for point estimation and plotting as "dots".
95
+ If {cmd:dots(p s)} is specified, a piecewise polynomial of degree {it:p} with {it:s} smoothness constraints is used.
96
+ The default is {cmd:dots(0 0)}, which corresponds to piecewise constant (canonical binscatter).
97
+ If {cmd:dots(T)} is specified, the default {cmd:dots(0 0)} is used unless the degree {it:p} and smoothness {it:s} selection
98
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
99
+ If {cmd:dots(F)} is specified, the dots are not included in the plot.
100
+ {p_end}
101
+
102
+ {p 4 8} {opt dotsgrid(dotsgridoption)} specifies the number and location of dots within each bin to be plotted.
103
+ Two options are available: {it:mean} and a {it:numeric} non-negative integer.
104
+ The option {opt dotsgrid(mean)} adds the sample average of {it:indvar} within each bin to the grid of evaluation points.
105
+ The option {opt dotsgrid(#)} adds {it:#} number of evenly-spaced points to the grid of evaluation points for each bin.
106
+ Both options can be used simultaneously: for example, {opt dotsgrid(mean 5)} generates six evaluation points
107
+ within each bin containing the sample mean of {it:indvar} within each bin and five evenly-spaced points.
108
+ Given this choice, the dots are point estimates evaluated over the selected grid within each bin.
109
+ The default is {opt dotsgrid(mean)}, which corresponds to one dot per bin evaluated at the sample average of {it:indvar} within each bin (canonical binscatter).
110
+ {p_end}
111
+
112
+ {p 4 8} {opt dotsplotopt(dotsoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the plotted dots.
113
+ {p_end}
114
+
115
+ {dlgtab:Line}
116
+
117
+ {p 4 8} {opt line(lineopt)} sets the degree of polynomial and the number of smoothness constraints
118
+ for plotting as a "line". If {cmd:line(p s)} is specified, a piecewise polynomial of
119
+ degree {it:p} with {it:s} smoothness constraints is used.
120
+ If {cmd:line(T)} is specified, {cmd:line(0 0)} is used unless the degree {it:p} and smoothness {it:s} selection
121
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
122
+ If {cmd:line(F)} or {cmd:line()} is specified, the line is not included in the plot.
123
+ The default is {cmd:line()}.
124
+ {p_end}
125
+
126
+ {p 4 8} {opt linegrid(#)} specifies the number of evaluation points of an evenly-spaced grid within
127
+ each bin used for evaluation of the point estimate set by the {cmd:line(p s)} option.
128
+ The default is {cmd:linegrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin for fitting/plotting the line.
129
+ {p_end}
130
+
131
+ {p 4 8} {opt lineplotopt(lineoption)} standard graphs options to be passed on to
132
+ the {help twoway:twoway} command to modify the appearance of the plotted line.
133
+ {p_end}
134
+
135
+ {dlgtab:Confidence Intervals}
136
+
137
+ {p 4 8} {opt ci(ciopt)} specifies the degree of polynomial and the number of smoothness constraints
138
+ for constructing confidence intervals. If {cmd:ci(p s)} is specified, a piecewise polynomial of
139
+ degree {it:p} with {it:s} smoothness constraints is used.
140
+ If {cmd:ci(T)} is specified, {cmd:ci(1 1)} is used unless the degree {it:p} and smoothness {it:s} selection
141
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
142
+ If {cmd:ci(F)} or {cmd:ci()} is specified, the confidence intervals are not included in the plot.
143
+ The default is {cmd:ci()}.
144
+ {p_end}
145
+
146
+ {p 4 8} {opt cigrid(cigridoption)} specifies the number and location of evaluation points in the grid
147
+ used to construct the confidence intervals set by the {opt ci(p s)} option.
148
+ Two options are available: {it:mean} and a {it:numeric} non-negative integer.
149
+ The option {opt cigrid(mean)} adds the sample average of {it:indvar} within each bin to the grid of evaluation points.
150
+ The option {opt cigrid(#)} adds {it:#} number of evenly-spaced points to the grid of evaluation points for each bin.
151
+ Both options can be used simultaneously: for example, {opt cigrid(mean 5)} generates six evaluation points within each bin containing the sample mean of {it:indvar} within each bin and five evenly-spaced points.
152
+ The default is {opt cigrid(mean)}, which corresponds to one evaluation point set at the sample average of {it:indvar} within each bin for confidence interval construction.
153
+ {p_end}
154
+
155
+ {p 4 8} {opt ciplotopt(rcapoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the confidence intervals.
156
+ {p_end}
157
+
158
+ {dlgtab:Confidence Band}
159
+
160
+ {p 4 8} {opt cb(cbopt)} specifies the degree of polynomial and the number of smoothness constraints
161
+ for constructing the confidence band. If {cmd:cb(p s)} is specified, a piecewise polynomial of
162
+ degree {it:p} with {it:s} smoothness constraints is used.
163
+ If the option {cmd:cb(T)} is specified, {cmd:cb(1 1)} is used unless the degree {it:p} and smoothness {it:s} selection
164
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
165
+ If {cmd:cb(F)} or {cmd:cb()} is specified, the confidence band is not included in the plot.
166
+ The default is {cmd:cb()}.
167
+ {p_end}
168
+
169
+ {p 4 8} {opt cbgrid(#)} specifies the number of evaluation points of an evenly-spaced grid within each bin
170
+ used for evaluation of the point estimate set by the {cmd:cb(p s)} option.
171
+ The default is {cmd:cbgrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin for confidence band construction.
172
+ {p_end}
173
+
174
+ {p 4 8} {opt cbplotopt(rareaoption)} standard graphs options to be passed on to
175
+ the {help twoway:twoway} command to modify the appearance of the confidence band.
176
+ {p_end}
177
+
178
+ {dlgtab:Global Polynomial Regression}
179
+
180
+ {p 4 8} {opt polyreg(p)} sets the degree {it:p} of a global polynomial regression model for plotting.
181
+ By default, this fit is not included in the plot unless explicitly specified.
182
+ Recommended specification is {cmd:polyreg(3)}, which adds a cubic polynomial fit of the regression function of interest to the binned scatter plot.
183
+ {p_end}
184
+
185
+ {p 4 8} {opt polyreggrid(#)} specifies the number of evaluation points of an evenly-spaced grid
186
+ within each bin used for evaluation of the point estimate set by the {cmd:polyreg(p)} option.
187
+ The default is {cmd:polyreggrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin for confidence interval construction.
188
+ {p_end}
189
+
190
+ {p 4 8} {opt polyregcigrid(#)} specifies the number of evaluation points of an evenly-spaced grid within each bin used for constructing confidence intervals based on polynomial regression set by the {cmd:polyreg(p)} option.
191
+ The default is {cmd:polyregcigrid(0)}, which corresponds to not plotting confidence intervals for the global polynomial regression approximation.
192
+ {p_end}
193
+
194
+ {p 4 8} {opt polyregplotopt(lineoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the global polynomial regression fit.
195
+ {p_end}
196
+
197
+ {dlgtab:Subgroup Analysis}
198
+
199
+ {p 4 8} {opt by(varname)} specifies the variable containing the group indicator to perform subgroup analysis;
200
+ both numeric and string variables are supported.
201
+ When {opt by(varname)} is specified, {cmdab:binslogit} implements estimation and inference for each subgroup separately,
202
+ but produces a common binned scatter plot.
203
+ By default, the binning structure is selected for each subgroup separately,
204
+ but see the option {cmd:samebinsby} below for imposing a common binning structure across subgroups.
205
+ {p_end}
206
+
207
+ {p 4 8} {cmd:bycolors(}{it:{help colorstyle}list}{cmd:)} specifies an ordered list of colors
208
+ for plotting each subgroup series defined by the option {opt by()}.
209
+ {p_end}
210
+
211
+ {p 4 8} {cmd:bysymbols(}{it:{help symbolstyle}list}{cmd:)} specifies an ordered list of symbols
212
+ for plotting each subgroup series defined by the option {opt by()}.
213
+ {p_end}
214
+
215
+ {p 4 8} {cmd:bylpatterns(}{it:{help linepatternstyle}list}{cmd:)} specifies an ordered list of line patterns
216
+ for plotting each subgroup series defined by the option {opt by()}.
217
+ {p_end}
218
+
219
+ {dlgtab:Binning/Degree/Smoothness Selection}
220
+
221
+ {p 4 8} {opt nbins(nbinsopt)} sets the number of bins for partitioning/binning of {it:indvar}.
222
+ If {cmd:nbins(T)} or {cmd:nbins()} (default) is specified, the number of bins is selected via the companion command {help binsregselect:binsregselect}
223
+ in a data-driven, optimal way whenever possible. If a {help numlist:numlist} with more than one number is specified,
224
+ the number of bins is selected within this list via the companion command {help binsregselect:binsregselect}.
225
+ {p_end}
226
+
227
+ {p 4 8} {opt binspos(position)} specifies the position of binning knots.
228
+ The default is {cmd:binspos(qs)}, which corresponds to quantile-spaced binning (canonical binscatter).
229
+ Other options are: {cmd:es} for evenly-spaced binning, or a {help numlist} for manual specification of
230
+ the positions of inner knots (which must be within the range of {it:indvar}).
231
+ {p_end}
232
+
233
+ {p 4 8} {opt binsmethod(method)} specifies the method for data-driven selection of the number of bins via the companion command {help binsregselect:binsregselect}.
234
+ The default is {cmd:binsmethod(dpi)}, which corresponds to the IMSE-optimal direct plug-in rule.
235
+ The other option is: {cmd:rot} for rule of thumb implementation.
236
+ {p_end}
237
+
238
+ {p 4 8} {opt nbinsrot(#)} specifies an initial number of bins value used to construct the DPI number of bins selector.
239
+ If not specified, the data-driven ROT selector is used instead.
240
+ {p_end}
241
+
242
+ {p 4 8} {opt samebinsby} forces a common partitioning/binning structure across all subgroups specified by the option {cmd:by()}.
243
+ The knots positions are selected according to the option {cmd:binspos()} and using the full sample.
244
+ If {cmd:nbins()} is not specified, then the number of bins is selected via the companion command
245
+ {help binsregselect:binsregselect} and using the full sample.
246
+ {p_end}
247
+
248
+ {p 4 8} {opt randcut(#)} specifies the upper bound on a uniformly distributed variable used to draw a subsample
249
+ for bins/degree/smoothness selection.
250
+ Observations for which {cmd:runiform()<=#} are used. # must be between 0 and 1.
251
+ By default, max(5,000, 0.01n) observations are used if the samples size n>5,000.
252
+ {p_end}
253
+
254
+ {p 4 8} {opt pselect(numlist)} specifies a list of numbers within which the degree of polynomial {it:p} for
255
+ point estimation is selected. Piecewise polynomials of the selected optimal degree {it:p}
256
+ are used to construct dots or line if {cmd:dots(T)} or {cmd:line(T)} is specified,
257
+ whereas piecewise polynomials of degree {it:p+1} are used to construct confidence intervals
258
+ or confidence band if {cmd:ci(T)} or {cmd:cb(T)} is specified.
259
+ {p_end}
260
+
261
+ {p 4 8} {opt sselect(numlist)} specifies a list of numbers within which
262
+ the number of smoothness constraints {it:s}
263
+ for point estimation. Piecewise polynomials with the selected optimal
264
+ {it:s} smoothness constraints are used to construct dots or line
265
+ if {cmd:dots(T)} or {cmd:line(T)} is specified,
266
+ whereas piecewise polynomials with {it:s+1} constraints are used to construct
267
+ confidence intervals or confidence band if {cmd:ci(T)} or {cmd:cb(T)} is specified.
268
+ If not specified, for each value {it:p} supplied in the
269
+ option {cmd:pselect()}, only the piecewise polynomial with the maximum smoothness is considered, i.e., {it:s=p}.
270
+ {p_end}
271
+
272
+ {p 4 8} Note: To implement the degree or smoothness selection, in addition to {cmd:pselect()}
273
+ or {cmd:sselect()}, {cmd:nbins(#)} must be specified.
274
+ {p_end}
275
+
276
+ {dlgtab:Simulation}
277
+
278
+ {p 4 8} {opt nsims(#)} specifies the number of random draws for constructing confidence bands.
279
+ The default is {cmd:nsims(500)}, which corresponds to 500 draws from a standard Gaussian random vector of size [(p+1)*J - (J-1)*s].
280
+ A large number of random draws is recommended to obtain the final results.
281
+ {p_end}
282
+
283
+ {p 4 8} {opt simsgrid(#)} specifies the number of evaluation points of an evenly-spaced grid
284
+ within each bin used for evaluation of the supremum operation needed to construct confidence bands.
285
+ The default is {cmd:simsgrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin
286
+ for approximating the supremum operator.
287
+ A large number of evaluation points is recommended to obtain the final results.
288
+ {p_end}
289
+
290
+ {p 4 8} {opt simsseed(#)} sets the seed for simulations.
291
+ {p_end}
292
+
293
+ {dlgtab:Mass Points and Degrees of Freedom}
294
+
295
+ {p 4 8} {opt dfcheck(n1 n2)} sets cutoff values for minimum effective sample size checks,
296
+ which take into account the number of unique values of {it:indvar} (i.e., adjusting for the number of mass points),
297
+ number of clusters, and degrees of freedom of the different statistical models considered.
298
+ The default is {cmd:dfcheck(20 30)}. See Cattaneo, Crump, Farrell and Feng (2022b) for more details.
299
+ {p_end}
300
+
301
+ {p 4 8} {opt masspoints(masspointsoption)} specifies how mass points in {it:indvar} are handled.
302
+ By default, all mass point and degrees of freedom checks are implemented.
303
+ Available options:
304
+ {p_end}
305
+ {p 8 8} {opt masspoints(noadjust)} omits mass point checks and the corresponding effective sample size adjustments.{p_end}
306
+ {p 8 8} {opt masspoints(nolocalcheck)} omits within-bin mass point and degrees of freedom checks.{p_end}
307
+ {p 8 8} {opt masspoints(off)} sets {opt masspoints(noadjust)} and {opt masspoints(nolocalcheck)} simultaneously.{p_end}
308
+ {p 8 8} {opt masspoints(veryfew)} forces the command to proceed as if {it:indvar} has only a few number of mass points (i.e., distinct values).
309
+ In other words, forces the command to proceed as if the mass point and degrees of freedom checks were failed.{p_end}
310
+
311
+ {dlgtab:Standard Error}
312
+
313
+ {p 4 8} {cmd:vce(}{it:{help vcetype}}{cmd:)} specifies the {it:vcetype} for variance estimation used by
314
+ the command {help logit##options:logit}.
315
+ The default is {cmd:vce(robust)}.
316
+ {p_end}
317
+
318
+ {p 4 8} {opt asyvar(on/off)} specifies the method used to compute standard errors.
319
+ If {cmd:asyvar(on)} is specified, the standard error of the nonparametric component is used and the uncertainty related to other control variables {it:othercovs} is omitted.
320
+ Default is {cmd:asyvar(off)}, that is, the uncertainty related to {it:othercovs} is taken into account.
321
+ {p_end}
322
+
323
+ {dlgtab:Other Options}
324
+
325
+ {p 4 8} {opt level(#)} sets the nominal confidence level for confidence interval and confidence band estimation. Default is {cmd:level(95)}.
326
+ {p_end}
327
+
328
+ {p 4 8} {opt logitopt(logit_option)} options to be passed on to the command {help logit##options:logit}.
329
+ For example, options that control for the optimization process can be added here.
330
+ {p_end}
331
+
332
+ {p 4 8}{opt usegtools(on/off)} forces the use of several commands in the community-distributed Stata package {cmd:gtools} to speed the computation up, if {it:on} is specified.
333
+ Default is {cmd:usegtools(off)}.
334
+ {p_end}
335
+
336
+ {p 4 8} For more information about the package {cmd:gtools}, please see {browse "https://gtools.readthedocs.io/en/latest/index.html":https://gtools.readthedocs.io/en/latest/index.html}.
337
+ {p_end}
338
+
339
+ {p 4 8} {opt noplot} omits binscatter plotting.
340
+ {p_end}
341
+
342
+ {p 4 8} {opt savedata(filename)} specifies a filename for saving all data underlying the binscatter plot (and more).
343
+ {p_end}
344
+
345
+ {p 4 8} {opt replace} overwrites the existing file when saving the graph data.
346
+ {p_end}
347
+
348
+ {p 4 8} {opt plotxrange(min max)} specifies the range of the x-axis for plotting. Observations outside the range are dropped in the plot.{p_end}
349
+
350
+ {p 4 8} {opt plotyrange(min max)} specifies the range of the y-axis for plotting. Observations outside the range are dropped in the plot.{p_end}
351
+
352
+ {p 4 8} {it:{help twoway_options}} any unrecognized options are appended to the end of the twoway command generating the binned scatter plot.
353
+ {p_end}
354
+
355
+
356
+ {marker examples}{...}
357
+ {title:Examples}
358
+
359
+ {p 4 8} Setup{p_end}
360
+ {p 8 8} . {stata sysuse auto}{p_end}
361
+
362
+ {p 4 8} Run a binscatter logit regression and report the plot{p_end}
363
+ {p 8 8} . {stata binslogit foreign weight mpg}{p_end}
364
+
365
+ {p 4 8} Add confidence intervals and confidence band{p_end}
366
+ {p 8 8} . {stata binslogit foreign weight mpg, ci(1 1) nbins(5)}{p_end}
367
+
368
+
369
+ {marker stored_results}{...}
370
+ {title:Stored results}
371
+
372
+ {synoptset 17 tabbed}{...}
373
+ {p2col 5 17 21 2: Scalars}{p_end}
374
+ {synopt:{cmd:e(N)}}number of observations{p_end}
375
+ {synopt:{cmd:e(level)}}confidence level{p_end}
376
+ {synopt:{cmd:e(dots_p)}}degree of polynomial for dots{p_end}
377
+ {synopt:{cmd:e(dots_s)}}smoothness of polynomial for dots{p_end}
378
+ {synopt:{cmd:e(line_p)}}degree of polynomial for line{p_end}
379
+ {synopt:{cmd:e(line_s)}}smoothness of polynomial for line{p_end}
380
+ {synopt:{cmd:e(ci_p)}}degree of polynomial for confidence interval{p_end}
381
+ {synopt:{cmd:e(ci_s)}}smoothness of polynomial for confidence interval{p_end}
382
+ {synopt:{cmd:e(cb_p)}}degree of polynomial for confidence band{p_end}
383
+ {synopt:{cmd:e(cb_s)}}smoothness of polynomial for confidence band{p_end}
384
+ {p2col 5 17 21 2: Matrices}{p_end}
385
+ {synopt:{cmd:e(N_by)}}number of observations for each group{p_end}
386
+ {synopt:{cmd:e(Ndist_by)}}number of distinct values for each group{p_end}
387
+ {synopt:{cmd:e(Nclust_by)}}number of clusters for each group{p_end}
388
+ {synopt:{cmd:e(nbins_by)}}number of bins for each group{p_end}
389
+ {synopt:{cmd:e(cval_by)}}critical value for each group, used for confidence bands{p_end}
390
+ {synopt:{cmd:e(imse_var_rot)}}variance constant in IMSE, ROT selection{p_end}
391
+ {synopt:{cmd:e(imse_bsq_rot)}}bias constant in IMSE, ROT selection{p_end}
392
+ {synopt:{cmd:e(imse_var_dpi)}}variance constant in IMSE, DPI selection{p_end}
393
+ {synopt:{cmd:e(imse_bsq_dpi)}}bias constant in IMSE, DPI selection{p_end}
394
+
395
+ {marker references}{...}
396
+ {title:References}
397
+
398
+ {p 4 8} Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2022a.
399
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Binscatter.pdf":On Binscatter}.
400
+ {it:arXiv:1902.09608}.
401
+ {p_end}
402
+
403
+ {p 4 8} Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2022b.
404
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Stata.pdf":Binscatter Regressions}.
405
+ {it:arXiv:1902.09615}.
406
+ {p_end}
407
+
408
+
409
+ {marker authors}{...}
410
+ {title:Authors}
411
+
412
+ {p 4 8} Matias D. Cattaneo, Princeton University, Princeton, NJ.
413
+ {browse "mailto:[email protected]":[email protected]}.
414
+ {p_end}
415
+
416
+ {p 4 8} Richard K. Crump, Federal Reserve Band of New York, New York, NY.
417
+ {browse "mailto:[email protected]":[email protected]}.
418
+ {p_end}
419
+
420
+ {p 4 8} Max H. Farrell, University of Chicago, Chicago, IL.
421
+ {browse "mailto:[email protected]":[email protected]}.
422
+ {p_end}
423
+
424
+ {p 4 8} Yingjie Feng, Tsinghua University, Beijing, China.
425
+ {browse "mailto:[email protected]":[email protected]}.
426
+ {p_end}
427
+
110/replication_package/replication/ado/plus/b/binsprobit.ado ADDED
@@ -0,0 +1,2390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *! version 1.2 09-Oct-2022
2
+
3
+ capture program drop binsprobit
4
+ program define binsprobit, eclass
5
+ version 13
6
+
7
+ syntax varlist(min=2 numeric fv ts) [if] [in] [fw pw] [, deriv(integer 0) at(string asis) nolink ///
8
+ probitopt(string asis) ///
9
+ dots(string) dotsgrid(string) dotsplotopt(string asis) ///
10
+ line(string) linegrid(integer 20) lineplotopt(string asis) ///
11
+ ci(string) cigrid(string) ciplotopt(string asis) ///
12
+ cb(string) cbgrid(integer 20) cbplotopt(string asis) ///
13
+ polyreg(string) polyreggrid(integer 20) polyregcigrid(integer 0) polyregplotopt(string asis) ///
14
+ by(varname) bycolors(string asis) bysymbols(string asis) bylpatterns(string asis) ///
15
+ nbins(string) binspos(string) binsmethod(string) nbinsrot(string) ///
16
+ pselect(numlist integer >=0) sselect(numlist integer >=0) ///
17
+ samebinsby randcut(numlist max=1 >=0 <=1) ///
18
+ nsims(integer 500) simsgrid(integer 20) simsseed(numlist integer max=1 >=0) ///
19
+ dfcheck(numlist integer max=2 >=0) masspoints(string) usegtools(string) ///
20
+ vce(passthru) level(real 95) asyvar(string) ///
21
+ noplot savedata(string asis) replace ///
22
+ plotxrange(numlist asc max=2) plotyrange(numlist asc max=2) *]
23
+
24
+ *********************************************
25
+ * Regularization constant (for checking only)
26
+ local qrot=2
27
+
28
+ **************************************
29
+ * Create weight local
30
+ if ("`weight'"!="") {
31
+ local wt [`weight'`exp']
32
+ local wtype=substr("`weight'",1,1)
33
+ }
34
+
35
+ **********************
36
+ ** Extract options ***
37
+ **********************
38
+ * report the results for the cond. mean model?
39
+ if ("`link'"!="") local transform "F"
40
+ else local transform "T"
41
+
42
+ * default vce, clustered?
43
+ if ("`vce'"=="") local vce "vce(robust)"
44
+ local vcetemp: subinstr local vce "vce(" "", all
45
+ local vcetemp: subinstr local vcetemp ")" "", all
46
+ tokenize "`vcetemp'"
47
+ if ("`1'"=="cl"|"`1'"=="clu"|"`1'"=="clus"|"`1'"=="clust"| ///
48
+ "`1'"=="cluste"|"`1'"=="cluster") {
49
+ local clusterON "T" /* Mark cluster is specified */
50
+ local clustervar `2'
51
+ }
52
+ if ("`vce'"=="vce(oim)"|"`vce'"=="vce(opg)") local vce_select "vce(ols)"
53
+ else local vce_select "`vce'"
54
+
55
+ if ("`asyvar'"=="") local asyvar "off"
56
+
57
+ if ("`binsmethod'"=="rot") local binsmethod "ROT"
58
+ if ("`binsmethod'"=="dpi") local binsmethod "DPI"
59
+ if ("`binsmethod'"=="") local binsmethod "DPI"
60
+ if ("`binspos'"=="es") local binspos "ES"
61
+ if ("`binspos'"=="qs") local binspos "QS"
62
+ if ("`binspos'"=="") local binspos "QS"
63
+
64
+
65
+ * analyze options related to degrees *************
66
+ if ("`dots'"!="T"&"`dots'"!="F"&"`dots'"!="") {
67
+ numlist "`dots'", integer max(2) range(>=0)
68
+ local dots=r(numlist)
69
+ }
70
+ if ("`line'"!="T"&"`line'"!="F"&"`line'"!="") {
71
+ numlist "`line'", integer max(2) range(>=0)
72
+ local line=r(numlist)
73
+ }
74
+ if ("`ci'"!="T"&"`ci'"!="F"&"`ci'"!="") {
75
+ numlist "`ci'", integer max(2) range(>=0)
76
+ local ci=r(numlist)
77
+ }
78
+ if ("`cb'"!="T"&"`cb'"!="F"&"`cb'"!="") {
79
+ numlist "`cb'", integer max(2) range(>=0)
80
+ local cb=r(numlist)
81
+ }
82
+
83
+
84
+ if ("`dots'"=="F") { /* shut down dots */
85
+ local dots ""
86
+ local dotsgrid 0
87
+ }
88
+ if ("`line'"=="F") local line ""
89
+ if ("`ci'"=="F") local ci ""
90
+ if ("`cb'"=="F") local cb ""
91
+
92
+ ***************************************************************
93
+ * 4 cases: select J, select p, user specified both, and error
94
+ local selection ""
95
+
96
+ * analyze nbins
97
+ if ("`nbins'"=="T") local nbins=0
98
+ local len_nbins=0
99
+ if ("`nbins'"!=""&"`nbins'"!="F") {
100
+ numlist "`nbins'", integer sort
101
+ local nbins=r(numlist)
102
+ local len_nbins: word count `nbins'
103
+ }
104
+
105
+ * analyze numlist in pselect and sselect
106
+ local len_p=0
107
+ local len_s=0
108
+
109
+ if ("`pselect'"!="") {
110
+ numlist "`pselect'", integer range(>=`deriv') sort
111
+ local plist=r(numlist)
112
+ }
113
+
114
+ if ("`sselect'"!="") {
115
+ numlist "`sselect'", integer range(>=0) sort
116
+ local slist=r(numlist)
117
+ }
118
+
119
+ local len_p: word count `plist'
120
+ local len_s: word count `slist'
121
+
122
+ if (`len_p'==1&`len_s'==0) {
123
+ local slist `plist'
124
+ local len_s=1
125
+ }
126
+ if (`len_p'==0&`len_s'==1) {
127
+ local plist `slist'
128
+ local len_p=1
129
+ }
130
+
131
+ if ("`binspos'"!="ES"&"`binspos'"!="QS") {
132
+ if ("`nbins'"!=""|"`pselect'"!=""|"`sselect'"!="") {
133
+ di as error "nbins(), pselect() or sselect() incorrectly specified."
134
+ exit
135
+ }
136
+ }
137
+
138
+ * 1st case: select J
139
+ if (("`nbins'"=="0"|`len_nbins'>1|"`nbins'"=="")&("`binspos'"=="ES"|"`binspos'"=="QS")) local selection "J"
140
+ if ("`selection'"=="J") {
141
+ if (`len_p'>1|`len_s'>1) {
142
+ if ("`nbins'"=="") {
143
+ di as error "nbins() must be specified for degree/smoothness selection."
144
+ exit
145
+ }
146
+ else {
147
+ di as error "Only one p and one s are allowed to select # of bins."
148
+ exit
149
+ }
150
+ }
151
+ if ("`plist'"=="") local plist=`deriv'
152
+ if ("`slist'"=="") local slist=`plist'
153
+ if ("`dots'"!=""&"`dots'"!="T"&"`dots'"!="F") { /* respect user-specified dots */
154
+ local plist: word 1 of `dots'
155
+ local slist: word 2 of `dots'
156
+ if ("`slist'"=="") local slist `plist'
157
+ }
158
+ if ("`dots'"==""|"`dots'"=="T") local dots `plist' `slist' /* selection is based on dots */
159
+ if ("`line'"=="T") local line `plist' `slist'
160
+ if ("`ci'"=="T") local ci `=`plist'+1' `=`slist'+1'
161
+ if ("`cb'"=="T") local cb `=`plist'+1' `=`slist'+1'
162
+ local len_p=1
163
+ local len_s=1
164
+ } /* e.g., binsreg y x, nbins(a b) or nbins(T) or pselect(a) nbins(T) */
165
+
166
+
167
+ * 2nd case: select P (at least for one object)
168
+ if ("`selection'"!="J" & ("`dots'"==""|"`dots'"=="T"|"`line'"=="T"|"`ci'"=="T"|"`cb'"=="T")) {
169
+ local pselectOK "T" /* p selection CAN be turned on as long as one of the four is T */
170
+ }
171
+
172
+ if ("`pselectOK'"=="T" & `len_nbins'==1 & (`len_p'>1|`len_s'>1)) {
173
+ local selection "P"
174
+ } /* e.g., binsreg y x, pselect(a b) or pselect() dots(T) */
175
+
176
+ * 3rd case: completely user-specified J and p
177
+ if ((`len_p'<=1&`len_s'<=1) & "`selection'"!="J") {
178
+ local selection "NA"
179
+ if ("`dots'"==""|"`dots'"=="T") {
180
+ if (`len_p'==1&`len_s'==1) local dots `plist' `slist'
181
+ else local dots `deriv' `deriv' /* e.g., binsreg y x or , dots(0 0) nbins(20) */
182
+ }
183
+ tokenize `dots'
184
+ if ("`2'"=="") local 2 `1'
185
+ if ("`line'"=="T") {
186
+ if (`len_p'==1&`len_s'==1) local line `plist' `slist'
187
+ else local line `dots'
188
+ }
189
+ if ("`ci'"=="T") {
190
+ if (`len_p'==1&`len_s'==1) local ci `=`plist'+1' `=`slist'+1'
191
+ else local ci `=`1'+1' `=`2'+1'
192
+ }
193
+ if ("`cb'"=="T") {
194
+ if (`len_p'==1&`len_s'==1) local cb `=`plist'+1' `=`slist'+1'
195
+ else local cb `=`1'+1' `=`2'+1'
196
+ }
197
+ }
198
+
199
+ * exclude all other cases
200
+ if ("`selection'"=="") {
201
+ di as error "Degree, smoothness, or # of bins are not correctly specified."
202
+ exit
203
+ }
204
+
205
+ ****** Now, extract from dots, line, etc. ************
206
+ * dots
207
+ tokenize `dots'
208
+ local dots_p "`1'"
209
+ local dots_s "`2'"
210
+ if ("`dots_p'"==""|"`dots_p'"=="T") local dots_p=.
211
+ if ("`dots_s'"=="") local dots_s `dots_p'
212
+
213
+ if ("`dotsgrid'"=="") local dotsgrid "mean"
214
+ local dotsngrid_mean=0
215
+ if (strpos("`dotsgrid'","mean")!=0) {
216
+ local dotsngrid_mean=1
217
+ local dotsgrid: subinstr local dotsgrid "mean" "", all
218
+ }
219
+ if (wordcount("`dotsgrid'")==0) local dotsngrid=0
220
+ else {
221
+ confirm integer n `dotsgrid'
222
+ local dotsngrid `dotsgrid'
223
+ }
224
+ local dotsntot=`dotsngrid_mean'+`dotsngrid'
225
+
226
+
227
+ * line
228
+ tokenize `line'
229
+ local line_p "`1'"
230
+ local line_s "`2'"
231
+ local linengrid `linegrid'
232
+ if ("`line'"=="") local linengrid=0
233
+ if ("`line_p'"==""|"`line_p'"=="T") local line_p=.
234
+ if ("`line_s'"=="") local line_s `line_p'
235
+
236
+ * ci
237
+ if ("`cigrid'"=="") local cigrid "mean"
238
+ local cingrid_mean=0
239
+ if (strpos("`cigrid'","mean")!=0) {
240
+ local cingrid_mean=1
241
+ local cigrid: subinstr local cigrid "mean" "", all
242
+ }
243
+ if (wordcount("`cigrid'")==0) local cingrid=0
244
+ else {
245
+ confirm integer n `cigrid'
246
+ local cingrid `cigrid'
247
+ }
248
+ local cintot=`cingrid_mean'+`cingrid'
249
+
250
+ tokenize `ci'
251
+ local ci_p "`1'"
252
+ local ci_s "`2'"
253
+ if ("`ci'"=="") local cintot=0
254
+ if ("`ci_p'"==""|"`ci_p'"=="T") local ci_p=.
255
+ if ("`ci_s'"=="") local ci_s `ci_p'
256
+
257
+ * cb
258
+ tokenize `cb'
259
+ local cb_p "`1'"
260
+ local cb_s "`2'"
261
+ local cbngrid `cbgrid'
262
+ if ("`cb'"=="") local cbngrid=0
263
+ if ("`cb_p'"==""|"`cb_p'"=="T") local cb_p=.
264
+ if ("`cb_s'"=="") local cb_s `cb_p'
265
+
266
+ * Add warnings about degrees for estimation and inference
267
+ if ("`selection'"=="J") {
268
+ if ("`ci_p'"!=".") {
269
+ if (`ci_p'<=`dots_p') {
270
+ local ci_p=`dots_p'+1
271
+ local ci_s=`ci_p'
272
+ di as text "Warning: Degree for ci() has been changed. It must be greater than the degree for dots()."
273
+ }
274
+ }
275
+ if ("`cb_p'"!=".") {
276
+ if (`cb_p'<=`dots_p') {
277
+ local cb_p=`dots_p'+1
278
+ local cb_s=`cb_p'
279
+ di as text "Warning: Degree for cb() has been changed. It must be greater than the degree for dots()."
280
+ }
281
+ }
282
+ }
283
+ if ("`selection'"=="NA") {
284
+ if ("`ci'"!=""|"`cb'"!="") {
285
+ di as text "Warning: Confidence intervals/bands are valid when nbins() is much larger than IMSE-optimal choice."
286
+ }
287
+ }
288
+ * if selection==P, compare ci_p/cb_p with P_opt later
289
+
290
+ * poly fit
291
+ local polyregngrid `polyreggrid'
292
+ local polyregcingrid `polyregcigrid'
293
+ if ("`polyreg'"!="") {
294
+ confirm integer n `polyreg'
295
+ }
296
+ else {
297
+ local polyregngrid=0
298
+ }
299
+
300
+ * range of x axis and y axis?
301
+ tokenize `plotxrange'
302
+ local min_xr "`1'"
303
+ local max_xr "`2'"
304
+ tokenize `plotyrange'
305
+ local min_yr "`1'"
306
+ local max_yr "`2'"
307
+
308
+
309
+ * Simuls
310
+ local simsngrid=`simsgrid'
311
+
312
+ * Record if nbins specified by users, set default
313
+ local nbins_full `nbins' /* local save common nbins */
314
+ if ("`selection'"=="NA") local binselectmethod "User-specified"
315
+ else {
316
+ if ("`binsmethod'"=="DPI") local binselectmethod "IMSE-optimal plug-in choice"
317
+ if ("`binsmethod'"=="ROT") local binselectmethod "IMSE-optimal rule-of-thumb choice"
318
+ if ("`selection'"=="J") local binselectmethod "`binselectmethod' (select # of bins)"
319
+ if ("`selection'"=="P") local binselectmethod "`binselectmethod' (select degree and smoothness)"
320
+ }
321
+
322
+ * Mass point check?
323
+ if ("`masspoints'"=="") {
324
+ local massadj "T"
325
+ local localcheck "T"
326
+ }
327
+ else if ("`masspoints'"=="off") {
328
+ local massadj "F"
329
+ local localcheck "F"
330
+ }
331
+ else if ("`masspoints'"=="noadjust") {
332
+ local massadj "F"
333
+ local localcheck "T"
334
+ }
335
+ else if ("`masspoints'"=="nolocalcheck") {
336
+ local massadj "T"
337
+ local localcheck "F"
338
+ }
339
+ else if ("`masspoints'"=="veryfew") {
340
+ local fewmasspoints "T" /* count mass point, but turn off checks */
341
+ }
342
+
343
+ * extract dfcheck
344
+ if ("`dfcheck'"=="") local dfcheck 20 30
345
+ tokenize `dfcheck'
346
+ local dfcheck_n1 "`1'"
347
+ local dfcheck_n2 "`2'"
348
+
349
+ * evaluate at w from another dataset?
350
+ if (`"`at'"'!=`""'&`"`at'"'!=`"mean"'&`"`at'"'!=`"median"'&`"`at'"'!=`"0"') local atwout "user"
351
+
352
+ * use gtools commands instead?
353
+ if ("`usegtools'"=="off") local usegtools ""
354
+ if ("`usegtools'"=="on") local usegtools usegtools
355
+ if ("`usegtools'"!="") {
356
+ capture which gtools
357
+ if (_rc) {
358
+ di as error "Gtools package not installed."
359
+ exit
360
+ }
361
+ local localcheck "F"
362
+ local sel_gtools "on"
363
+ * use gstats tab instead of tabstat/collapse
364
+ * use gquantiles instead of _pctile
365
+ * use gunique instead of binsreg_uniq
366
+ * use fasterxtile instead of irecode (within binsreg_irecode)
367
+ * shut down local checks & do not sort
368
+ }
369
+
370
+ *************************
371
+ **** error checks *******
372
+ *************************
373
+ if (`deriv'<0) {
374
+ di as error "Derivative incorrectly specified."
375
+ exit
376
+ }
377
+ if (`deriv'>1&"`transform'"=="T") {
378
+ di as error "deriv cannot be greater than 1 if the conditional probability is requested."
379
+ exit
380
+ }
381
+ if (`dotsngrid'<0|`linengrid'<0|`cingrid'<0|`cbngrid'<0|`simsngrid'<0) {
382
+ di as error "Number of evaluation points incorrectly specified."
383
+ exit
384
+ }
385
+ if (`level'>100|`level'<0) {
386
+ di as error "Confidence level incorrectly specified."
387
+ exit
388
+ }
389
+ if ("`dots_p'"!=".") {
390
+ if (`dots_p'<`dots_s') {
391
+ di as error "p cannot be smaller than s."
392
+ exit
393
+ }
394
+ if (`dots_p'<`deriv') {
395
+ di as error "p for dots cannot be less than deriv."
396
+ exit
397
+ }
398
+ }
399
+ if ("`line_p'"!=".") {
400
+ if (`line_p'<`line_s') {
401
+ di as error "p cannot be smaller than s."
402
+ exit
403
+ }
404
+ if (`line_p'<`deriv') {
405
+ di as error "p for line cannot be less than deriv."
406
+ exit
407
+ }
408
+ }
409
+ if ("`ci_p'"!=".") {
410
+ if (`ci_p'<`ci_s') {
411
+ di as error "p cannot be smaller than s."
412
+ exit
413
+ }
414
+ if (`ci_p'<`deriv') {
415
+ di as error "p for CI cannot be less than deriv."
416
+ exit
417
+ }
418
+ }
419
+ if ("`cb_p'"!=".") {
420
+ if (`cb_p'<`cb_s') {
421
+ di as error "p cannot be smaller than s."
422
+ exit
423
+ }
424
+ if (`cb_p'<`deriv') {
425
+ di as error "p for CB cannot be less than deriv."
426
+ exit
427
+ }
428
+ }
429
+ if ("`polyreg'"!="") {
430
+ if (`polyreg'<`deriv') {
431
+ di as error "polyreg() cannot be less than deriv()."
432
+ exit
433
+ }
434
+ }
435
+
436
+ if (`"`savedata'"'!=`""') {
437
+ if ("`replace'"=="") {
438
+ confirm new file `"`savedata'.dta"'
439
+ }
440
+ if ("`plot'"!="") {
441
+ di as error "plot cannot be turned off if graph data are requested."
442
+ exit
443
+ }
444
+ }
445
+ if (`polyregcingrid'!=0&"`polyreg'"=="") {
446
+ di as error "polyreg() is missing."
447
+ exit
448
+ }
449
+ if ("`binsmethod'"!="DPI"&"`binsmethod'"!="ROT") {
450
+ di as error "binsmethod incorrectly specified."
451
+ exit
452
+ }
453
+ ******** END error checking ***************************
454
+
455
+ * Mark sample
456
+ preserve
457
+
458
+ * Parse varlist into y_var, x_var and w_var
459
+ tokenize `varlist'
460
+ fvrevar `1', tsonly
461
+ local y_var "`r(varlist)'"
462
+ local y_varname "`1'"
463
+ fvrevar `2', tsonly
464
+ local x_var "`r(varlist)'"
465
+ local x_varname "`2'"
466
+
467
+ macro shift 2
468
+ local w_var "`*'"
469
+ * read eval point for w from another file
470
+ if ("`atwout'"=="user") {
471
+ append using `at'
472
+ }
473
+
474
+ fvrevar `w_var', tsonly
475
+ local w_var "`r(varlist)'"
476
+ local nwvar: word count `w_var'
477
+
478
+ * Save the last obs in a vector and then drop it
479
+ tempname wuser /* a vector used to keep eval for w */
480
+ if ("`atwout'"=="user") {
481
+ mata: st_matrix("`wuser'", st_data(`=_N', "`w_var'"))
482
+ qui drop in `=_N'
483
+ }
484
+
485
+ * Get positions of factor vars
486
+ local indexlist ""
487
+ local i = 1
488
+ foreach v in `w_var' {
489
+ if strpos("`v'", ".") == 0 {
490
+ local indexlist `indexlist' `i'
491
+ }
492
+ local ++i
493
+ }
494
+
495
+ * add a default for at
496
+ if (`"`at'"'==""&`nwvar'>0) {
497
+ local at "mean"
498
+ }
499
+
500
+ marksample touse
501
+ markout `touse' `by', strok
502
+ qui keep if `touse'
503
+ local nsize=_N /* # of rows in the original dataset */
504
+
505
+ if ("`usegtools'"==""&("`masspoints'"!="off"|"`binspos'"=="QS")) {
506
+ if ("`:sortedby'"!="`x_var'") {
507
+ di as text in gr "Sorting dataset on `x_varname'..."
508
+ di as text in gr "Note: This step is omitted if dataset already sorted by `x_varname'."
509
+ sort `x_var', stable
510
+ }
511
+ local sorted "sorted"
512
+ }
513
+
514
+ if ("`wtype'"=="f") qui sum `x_var' `wt', meanonly
515
+ else qui sum `x_var', meanonly
516
+
517
+ local xmin=r(min)
518
+ local xmax=r(max)
519
+ local Ntotal=r(N) /* total sample size, with wt */
520
+ * define the support of plot
521
+ if ("`plotxrange'"!="") {
522
+ local xsc `plotxrange'
523
+ if (wordcount("`xsc'")==1) local xsc `xsc' `xmax'
524
+ }
525
+ else local xsc `xmin' `xmax'
526
+
527
+ * Effective sample size
528
+ local eN=`nsize'
529
+ * DO NOT check mass points and clusters outside loop unless needed
530
+
531
+ * Check number of unique byvals & create local storing byvals
532
+ local byvarname `by'
533
+ if "`by'"!="" {
534
+ capture confirm numeric variable `by'
535
+ if _rc {
536
+ local bystring "T"
537
+ * generate a numeric version
538
+ tempvar by
539
+ tempname bylabel
540
+ qui egen `by'=group(`byvarname'), lname(`bylabel')
541
+ }
542
+
543
+ local bylabel `:value label `by'' /* catch value labels for numeric by-vars too */
544
+
545
+ tempname byvalmatrix
546
+ qui tab `by', nofreq matrow(`byvalmatrix')
547
+
548
+ local bynum=r(r)
549
+ forvalues i=1/`bynum' {
550
+ local byvals `byvals' `=`byvalmatrix'[`i',1]'
551
+ }
552
+ }
553
+ else local bynum=1
554
+
555
+ * Default colors, symbols, linepatterns
556
+ if (`"`bycolors'"'==`""') local bycolors ///
557
+ navy maroon forest_green dkorange teal cranberry lavender ///
558
+ khaki sienna emidblue emerald brown erose gold bluishgray
559
+ if (`"`bysymbols'"'==`""') local bysymbols ///
560
+ O D T S + X A a | V o d s t x
561
+ if (`"`bylpatterns'"'==`""') {
562
+ forval i=1/`bynum' {
563
+ local bylpatterns `bylpatterns' solid
564
+ }
565
+ }
566
+
567
+ * Temp name in MATA
568
+ tempname xvec yvec byvec cluvec binedges
569
+ mata: `xvec'=st_data(., "`x_var'"); `yvec'=st_data(.,"`y_var'"); `byvec'=.; `cluvec'=.
570
+
571
+ *******************************************************
572
+ *** Mass point counting *******************************
573
+ tempname Ndistlist Nclustlist mat_imse_var_rot mat_imse_bsq_rot mat_imse_var_dpi mat_imse_bsq_dpi
574
+ mat `Ndistlist'=J(`bynum',1,.)
575
+ mat `Nclustlist'=J(`bynum',1,.)
576
+ * Matrices saving imse
577
+ mat `mat_imse_var_rot'=J(`bynum',1,.)
578
+ mat `mat_imse_bsq_rot'=J(`bynum',1,.)
579
+ mat `mat_imse_var_dpi'=J(`bynum',1,.)
580
+ mat `mat_imse_bsq_dpi'=J(`bynum',1,.)
581
+
582
+ if (`bynum'>1) mata: `byvec'=st_data(.,"`by'")
583
+ if ("`clusterON'"=="T") mata: `cluvec'=st_data(.,"`clustervar'")
584
+
585
+ ********************************************************
586
+ ********** Bins, based on FULL sample ******************
587
+ ********************************************************
588
+ * knotlist: inner knot seq; knotlistON: local, knot available before loop
589
+
590
+ tempname fullkmat /* matrix name for saving knots based on the full sample */
591
+
592
+ * Extract user-specified knot list
593
+ if ("`binspos'"!="ES"&"`binspos'"!="QS") {
594
+ capture numlist "`binspos'", ascending
595
+ if (_rc==0) {
596
+ local knotlistON "T"
597
+ local knotlist `binspos'
598
+ local nbins: word count `knotlist'
599
+ local first: word 1 of `knotlist'
600
+ local last: word `nbins' of `knotlist'
601
+ if (`first'<=`xmin'|`last'>=`xmax') {
602
+ di as error "Inner knots specified out of allowed range."
603
+ exit
604
+ }
605
+ else {
606
+ local nbins=`nbins'+1
607
+ local nbins_full `nbins'
608
+ local pos "user"
609
+
610
+ foreach el of local knotlist {
611
+ mat `fullkmat'=(nullmat(`fullkmat') \ `el')
612
+ }
613
+ mat `fullkmat'=(`xmin' \ `fullkmat' \ `xmax')
614
+ }
615
+ }
616
+ else {
617
+ di as error "numeric list incorrectly specified in binspos()."
618
+ exit
619
+ }
620
+ }
621
+
622
+ * Discrete x?
623
+ if ("`fewmasspoints'"!="") local fullfewobs "T"
624
+
625
+ * Bin selection using the whole sample if
626
+ if ("`fullfewobs'"==""&"`selection'"!="NA"&(("`by'"=="")|(("`by'"!="")&("`samebinsby'"!="")))) {
627
+ local selectfullON "T"
628
+ }
629
+
630
+ if ("`selectfullON'"=="T") {
631
+ local Ndist=.
632
+ if ("`massadj'"=="T") {
633
+ if ("`usegtools'"=="") {
634
+ mata: `binedges'=binsreg_uniq(`xvec', ., 1, "Ndist")
635
+ mata: mata drop `binedges'
636
+ }
637
+ else {
638
+ qui gunique `x_var'
639
+ local Ndist=r(unique)
640
+ }
641
+ local eN=min(`eN', `Ndist')
642
+ }
643
+ * # of clusters
644
+ local Nclust=.
645
+ if ("`clusterON'"=="T") {
646
+ if ("`usegtools'"=="") {
647
+ mata: st_local("Nclust", strofreal(rows(uniqrows(`cluvec'))))
648
+ }
649
+ else {
650
+ qui gunique `clustervar'
651
+ local Nclust=r(unique)
652
+ }
653
+ local eN=min(`eN', `Nclust') /* effective sample size */
654
+ }
655
+
656
+
657
+ * Check effective sample size
658
+ if ("`dots_p'"==".") local dotspcheck=6
659
+ else local dotspcheck=`dots_p'
660
+ * Check effective sample size
661
+ if ("`nbinsrot'"==""&(`eN'<=`dfcheck_n1'+`dotspcheck'+1+`qrot')) {
662
+ di as text in gr "Warning: Too small effective sample size for bin selection." ///
663
+ _newline _skip(9) "# of mass points or clusters used and by() option ignored."
664
+ local by ""
665
+ local byvals ""
666
+ local fullfewobs "T"
667
+ local binspos "QS" /* forced to be QS */
668
+ }
669
+ else {
670
+ local randcut1k `randcut'
671
+ if ("`randcut'"=="" & `Ntotal'>5000) {
672
+ local randcut1k=max(5000/`Ntotal', 0.01)
673
+ di as text in gr "Warning: To speed up computation, bin/degree selection uses a subsample of roughly max(5,000, 0.01n) observations if the sample size n>5000. To use the full sample, set randcut(1)."
674
+ }
675
+ if ("`selection'"=="J") {
676
+ qui binsregselect `y_var' `x_var' `w_var' `wt', deriv(`deriv') bins(`dots_p' `dots_s') nbins(`nbins_full') ///
677
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
678
+ binsmethod(`binsmethod') binspos(`binspos') nbinsrot(`nbinsrot') ///
679
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
680
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
681
+ if (e(nbinsrot_regul)==.) {
682
+ di as error "Bin selection fails."
683
+ exit
684
+ }
685
+ if ("`binsmethod'"=="ROT") {
686
+ local nbins=e(nbinsrot_regul)
687
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
688
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
689
+ }
690
+ else if ("`binsmethod'"=="DPI") {
691
+ local nbins=e(nbinsdpi)
692
+ mat `mat_imse_var_dpi'=J(`bynum',1,e(imse_var_dpi))
693
+ mat `mat_imse_bsq_dpi'=J(`bynum',1,e(imse_bsq_dpi))
694
+ if (`nbins'==.) {
695
+ local nbins=e(nbinsrot_regul)
696
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
697
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
698
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
699
+ }
700
+ }
701
+ }
702
+ else if ("`selection'"=="P") {
703
+ qui binsregselect `y_var' `x_var' `w_var' `wt', deriv(`deriv') nbins(`nbins_full') ///
704
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
705
+ pselect(`plist') sselect(`slist') ///
706
+ binsmethod(`binsmethod') binspos(`binspos') nbinsrot(`nbinsrot') ///
707
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
708
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
709
+ if (e(prot_regul)==.) {
710
+ di as error "Bin selection fails."
711
+ exit
712
+ }
713
+ if ("`binsmethod'"=="ROT") {
714
+ local binsp=e(prot_regul)
715
+ local binss=e(srot_regul)
716
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
717
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
718
+ }
719
+ else if ("`binsmethod'"=="DPI") {
720
+ local binsp=e(pdpi)
721
+ local binss=e(sdpi)
722
+ mat `mat_imse_var_dpi'=J(`bynum',1,e(imse_var_dpi))
723
+ mat `mat_imse_bsq_dpi'=J(`bynum',1,e(imse_bsq_dpi))
724
+ if (`binsp'==.) {
725
+ local binsp=e(prot_regul)
726
+ local binss=e(srot_regul)
727
+ mat `mat_imse_var_rot'=J(`bynum',1,e(imse_var_rot))
728
+ mat `mat_imse_bsq_rot'=J(`bynum',1,e(imse_bsq_rot))
729
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
730
+ }
731
+ }
732
+ if ("`dots'"=="T"|"`dots'"=="") {
733
+ local dots_p=`binsp'
734
+ local dots_s=`binss'
735
+ }
736
+ if ("`line'"=="T") {
737
+ local line_p=`binsp'
738
+ local line_s=`binss'
739
+ }
740
+ if ("`ci'"!="T"&"`ci'"!="") {
741
+ if (`ci_p'<=`binsp') {
742
+ local ci_p=`binsp'+1
743
+ local ci_s=`ci_p'
744
+ di as text "Warning: Degree for ci() has been changed. It must be greater than the IMSE-optimal degree."
745
+ }
746
+ }
747
+ if ("`ci'"=="T") {
748
+ local ci_p=`binsp'+1
749
+ local ci_s=`binss'+1
750
+ }
751
+ if ("`cb'"!="T"&"`cb'"!="") {
752
+ if (`cb_p'<=`binsp') {
753
+ local cb_p=`binsp'+1
754
+ local cb_s=`cb_p'
755
+ di as text "Warning: Degree for cb() has been changed. It must be greater than the IMSE-optimal degree."
756
+ }
757
+ }
758
+ if ("`cb'"=="T") {
759
+ local cb_p=`binsp'+1
760
+ local cb_s=`binss'+1
761
+ }
762
+ }
763
+ }
764
+ }
765
+
766
+ if (("`selectfullON'"=="T"|("`selection'"=="NA"&"`samebinsby'"!=""))&"`fullfewobs'"=="") {
767
+ * Save in a knot list
768
+ local knotlistON "T"
769
+ local nbins_full=`nbins'
770
+ if ("`binspos'"=="ES") {
771
+ local stepsize=(`xmax'-`xmin')/`nbins'
772
+ forvalues i=1/`=`nbins'+1' {
773
+ mat `fullkmat'=(nullmat(`fullkmat') \ `=`xmin'+`stepsize'*(`i'-1)')
774
+ }
775
+ }
776
+ else if ("`binspos'"=="QS") {
777
+ if (`nbins'==1) mat `fullkmat'=(`xmin' \ `xmax')
778
+ else {
779
+ binsreg_pctile `x_var' `wt', nq(`nbins') `usegtools'
780
+ mat `fullkmat'=(`xmin' \ r(Q) \ `xmax')
781
+ }
782
+ }
783
+ }
784
+
785
+ *** Placement name, for display ************
786
+ if ("`pos'"=="user") {
787
+ local binselectmethod "User-specified"
788
+ local placement "User-specified"
789
+ }
790
+ else if ("`binspos'"=="ES") {
791
+ local placement "Evenly-spaced"
792
+ }
793
+ else if ("`binspos'"=="QS") {
794
+ local placement "Quantile-spaced"
795
+ }
796
+
797
+ * NOTE: ALL checkings are put within the loop
798
+
799
+ * Set seed
800
+ if ("`simsseed'"!="") set seed `simsseed'
801
+
802
+ * alpha quantile (for two-sided CI)
803
+ local alpha=(100-(100-`level')/2)/100
804
+
805
+ ***************************************************************************
806
+ *************** Preparation before loop************************************
807
+ ***************************************************************************
808
+
809
+ ********** Prepare vars for plotting ********************
810
+ * names for mata objects storing graph data
811
+ * plotmat: final output (defined outside);
812
+ * plotmatby: output for each group
813
+ tempname plotmat plotmatby xsub ysub byindex xcatsub
814
+ tempname Xm Xm0 mata_fit mata_se /* temp name for mata obj */
815
+
816
+ * count the number of requested columns, record the positions
817
+ local ncolplot=1 /* 1st col reserved for group */
818
+ if ("`plot'"=="") {
819
+ if (`dotsntot'!=0) {
820
+ local dots_start=`ncolplot'+1
821
+ local dots_end=`ncolplot'+4
822
+ local ncolplot=`ncolplot'+4
823
+ }
824
+ if (`linengrid'!=0&"`fullfewobs'"=="") {
825
+ local line_start=`ncolplot'+1
826
+ local line_end=`ncolplot'+4
827
+ local ncolplot=`ncolplot'+4
828
+ }
829
+ if (`polyregngrid'!=0) {
830
+ local poly_start=`ncolplot'+1
831
+ local poly_end=`ncolplot'+4
832
+ local ncolplot=`ncolplot'+4
833
+ if (`polyregcingrid'!=0) {
834
+ local polyci_start=`ncolplot'+1
835
+ local polyci_end=`ncolplot'+5
836
+ local ncolplot=`ncolplot'+5
837
+ }
838
+ }
839
+ if (`cintot'!=0) {
840
+ local ci_start=`ncolplot'+1
841
+ local ci_end=`ncolplot'+5
842
+ local ncolplot=`ncolplot'+5
843
+ }
844
+ if (`cbngrid'!=0&"`fullfewobs'"=="") {
845
+ local cb_start=`ncolplot'+1
846
+ local cb_end=`ncolplot'+5
847
+ local ncolplot=`ncolplot'+5
848
+ }
849
+ }
850
+ mata: `plotmat'=J(0,`ncolplot',.)
851
+
852
+ * mark the (varying) last row (for plotting)
853
+ local bylast=0
854
+ *******************************************************************
855
+ * temp var: bin id
856
+ tempvar xcat
857
+ qui gen `xcat'=. in 1
858
+
859
+ * matrix names, for returns
860
+ tempname Nlist nbinslist cvallist
861
+
862
+ * local vars, for plotting
863
+ local counter_by=1
864
+ local plotnum=0 /* count the number of series, for legend */
865
+ if ("`by'"=="") local noby="noby"
866
+ local byvalnamelist "" /* save group name (value) */
867
+ local plotcmd "" /* plotting cmd */
868
+
869
+ ***************************************************************************
870
+ ******************* Now, enter the loop ***********************************
871
+ ***************************************************************************
872
+ foreach byval in `byvals' `noby' {
873
+ local conds ""
874
+ if ("`by'"!="") {
875
+ local conds "if `by'==`byval'" /* with "if" */
876
+ if ("`bylabel'"=="") local byvalname=`byval'
877
+ else {
878
+ local byvalname `: label `bylabel' `byval''
879
+ }
880
+ local byvalnamelist `" `byvalnamelist' `"`byvalname'"' "'
881
+ }
882
+ if (`bynum'>1) {
883
+ mata: `byindex'=`byvec':==`byval'
884
+ mata: `xsub'=select(`xvec',`byindex'); `ysub'=select(`yvec', `byindex')
885
+ }
886
+ else {
887
+ mata: `xsub'=`xvec'; `ysub'=`yvec'
888
+ }
889
+
890
+ * Subsample size
891
+ if ("`wtype'"=="f") sum `x_var' `conds' `wt', meanonly
892
+ else sum `x_var' `conds', meanonly
893
+
894
+ local xmin=r(min)
895
+ local xmax=r(max)
896
+ local N=r(N)
897
+ mat `Nlist'=(nullmat(`Nlist') \ `N')
898
+
899
+ * Effective sample size
900
+ if (`bynum'==1) local eN=`nsize'
901
+ else {
902
+ if ("`wtype'"!="f") local eN=r(N)
903
+ else {
904
+ qui count `conds'
905
+ local eN=r(N)
906
+ }
907
+ }
908
+
909
+ local Ndist=.
910
+ if ("`massadj'"=="T") {
911
+ if ("`usegtools'"=="") {
912
+ mata: `binedges'=binsreg_uniq(`xsub', ., 1, "Ndist")
913
+ mata: mata drop `binedges'
914
+ }
915
+ else {
916
+ qui gunique `x_var' `conds'
917
+ local Ndist=r(unique)
918
+ }
919
+ local eN=min(`eN', `Ndist')
920
+ mat `Ndistlist'[`counter_by',1]=`Ndist'
921
+ }
922
+
923
+ * # of clusters
924
+ local Nclust=.
925
+ if ("`clusterON'"=="T") {
926
+ if (`bynum'==1) {
927
+ if ("`usegtools'"=="") {
928
+ mata: st_local("Nclust", strofreal(rows(uniqrows(`cluvec'))))
929
+ }
930
+ else {
931
+ qui gunique `clustervar'
932
+ local Nclust=r(unique)
933
+ }
934
+ }
935
+ else {
936
+ if ("`usegtools'"=="") {
937
+ mata: st_local("Nclust", strofreal(rows(uniqrows(select(`cluvec', `byindex')))))
938
+ }
939
+ else {
940
+ qui gunique `clustervar' `conds'
941
+ local Nclust=r(unique)
942
+ }
943
+ }
944
+ local eN=min(`eN', `Nclust') /* effective SUBsample size */
945
+ mat `Nclustlist'[`counter_by',1]=`Nclust'
946
+ }
947
+
948
+ *********************************************************
949
+ ************** Prepare bins, within loop ****************
950
+ *********************************************************
951
+ if ("`pos'"!="user") local pos `binspos' /* initialize pos */
952
+ * Selection?
953
+ if ("`selection'"!="NA"&"`knotlistON'"!="T"&"`fullfewobs'"=="") {
954
+ * Check effective sample size
955
+ if ("`dots_p'"==".") local dotspcheck=6
956
+ else local dotspcheck=`dots_p'
957
+ if ("`nbinsrot'"==""&(`eN'<=`dfcheck_n1'+`dotspcheck'+1+`qrot')) {
958
+ di as text in gr "Warning: Too small effective sample size for bin selection." ///
959
+ _newline _skip(9) "# of mass points or clusters used."
960
+ local fewobs "T"
961
+ local nbins=`eN'
962
+ local pos "QS" /* forced to be QS */
963
+ }
964
+ else {
965
+ local randcut1k `randcut'
966
+ if ("`randcut'"=="" & `N'>5000) {
967
+ local randcut1k=max(5000/`N', 0.01)
968
+ di as text in gr "Warning: To speed up computation, bin/degree selection uses a subsample of roughly max(5,000, 0.01n) observations if the sample size n>5,000. To use the full sample, set randcut(1)."
969
+ }
970
+ if ("`selection'"=="J") {
971
+ qui binsregselect `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
972
+ bins(`dots_p' `dots_s') nbins(`nbins_full') ///
973
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
974
+ binsmethod(`binsmethod') binspos(`pos') nbinsrot(`nbinsrot') ///
975
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
976
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
977
+ if (e(nbinsrot_regul)==.) {
978
+ di as error "bin selection fails."
979
+ exit
980
+ }
981
+ if ("`binsmethod'"=="ROT") {
982
+ local nbins=e(nbinsrot_regul)
983
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
984
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
985
+ }
986
+ else if ("`binsmethod'"=="DPI") {
987
+ local nbins=e(nbinsdpi)
988
+ mat `mat_imse_bsq_dpi'[`counter_by',1]=e(imse_bsq_dpi)
989
+ mat `mat_imse_var_dpi'[`counter_by',1]=e(imse_var_dpi)
990
+ if (`nbins'==.) {
991
+ local nbins=e(nbinsrot_regul)
992
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
993
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
994
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
995
+ }
996
+ }
997
+ }
998
+ else if ("`selection'"=="P") {
999
+ qui binsregselect `y_var' `x_var' `w_var' `wt', deriv(`deriv') nbins(`nbins_full') ///
1000
+ absorb(`absorb') reghdfeopt(`reghdfeopt') ///
1001
+ pselect(`plist') sselect(`slist') ///
1002
+ binsmethod(`binsmethod') binspos(`binspos') nbinsrot(`nbinsrot') ///
1003
+ `vce' masspoints(`masspoints') dfcheck(`dfcheck_n1' `dfcheck_n2') ///
1004
+ numdist(`Ndist') numclust(`Nclust') randcut(`randcut1k') usegtools(`sel_gtools')
1005
+ if (e(prot_regul)==.) {
1006
+ di as error "bin selection fails."
1007
+ exit
1008
+ }
1009
+ if ("`binsmethod'"=="ROT") {
1010
+ local binsp=e(prot_regul)
1011
+ local binss=e(srot_regul)
1012
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
1013
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
1014
+ }
1015
+ else if ("`binsmethod'"=="DPI") {
1016
+ local binsp=e(pdpi)
1017
+ local binss=e(sdpi)
1018
+ mat `mat_imse_bsq_dpi'[`counter_by',1]=e(imse_bsq_dpi)
1019
+ mat `mat_imse_var_dpi'[`counter_by',1]=e(imse_var_dpi)
1020
+ if (`binsp'==.) {
1021
+ local binsp=e(prot_regul)
1022
+ local binss=e(srot_regul)
1023
+ mat `mat_imse_bsq_rot'[`counter_by',1]=e(imse_bsq_rot)
1024
+ mat `mat_imse_var_rot'[`counter_by',1]=e(imse_var_rot)
1025
+ di as text in gr "Warning: DPI selection fails. ROT choice used."
1026
+ }
1027
+ }
1028
+ if ("`dots'"=="T"|"`dots'"=="") {
1029
+ local dots_p=`binsp'
1030
+ local dots_s=`binss'
1031
+ }
1032
+ if ("`line'"=="T") {
1033
+ local line_p=`binsp'
1034
+ local line_s=`binss'
1035
+ }
1036
+ if ("`ci'"!="T"&"`ci'"!="") {
1037
+ if (`ci_p'<=`binsp') {
1038
+ local ci_p=`binsp'+1
1039
+ local ci_s=`ci_p'
1040
+ di as text "Warning: Degree for ci() has been changed. It must be greater than the IMSE-optimal degree."
1041
+ }
1042
+ }
1043
+ if ("`ci'"=="T") {
1044
+ local ci_p=`binsp'+1
1045
+ local ci_s=`binss'+1
1046
+ }
1047
+ if ("`cb'"!="T"&"`cb'"!="") {
1048
+ if (`cb_p'<=`binsp') {
1049
+ local cb_p=`binsp'+1
1050
+ local cb_s=`cb_p'
1051
+ di as text "Warning: Degree for cb() has been changed. It must be greater than the IMSE-optimal degree."
1052
+ }
1053
+ }
1054
+ if ("`cb'"=="T") {
1055
+ local cb_p=`binsp'+1
1056
+ local cb_s=`binss'+1
1057
+ }
1058
+ }
1059
+ }
1060
+ }
1061
+
1062
+ if ("`selection'"=="NA"|"`knotlistON'"=="T") local nbins=`nbins_full' /* add the universal nbins */
1063
+ *if ("`knotlistON'"=="T") local nbins=`nbins_full'
1064
+ if ("`fullfewobs'"!="") {
1065
+ local fewobs "T"
1066
+ local nbins=`eN'
1067
+ }
1068
+
1069
+ ******************************************************
1070
+ * Check effective sample size for each case **********
1071
+ ******************************************************
1072
+ if ("`fewobs'"!="T") {
1073
+ if ((`nbins'-1)*(`dots_p'-`dots_s'+1)+`dots_p'+1+`dfcheck_n2'>=`eN') {
1074
+ local fewobs "T" /* even though ROT available, treat it as few obs case */
1075
+ local nbins=`eN'
1076
+ local pos "QS"
1077
+ di as text in gr "Warning: Too small effective sample size for dots. # of mass points or clusters used."
1078
+ }
1079
+ if ("`line_p'"!=".") {
1080
+ if ((`nbins'-1)*(`line_p'-`line_s'+1)+`line_p'+1+`dfcheck_n2'>=`eN') {
1081
+ local line_fewobs "T"
1082
+ di as text in gr "Warning: Too small effective sample size for line."
1083
+ }
1084
+ }
1085
+ if ("`ci_p'"!=".") {
1086
+ if ((`nbins'-1)*(`ci_p'-`ci_s'+1)+`ci_p'+1+`dfcheck_n2'>=`eN') {
1087
+ local ci_fewobs "T"
1088
+ di as text in gr "Warning: Too small effective sample size for CI."
1089
+ }
1090
+ }
1091
+ if ("`cb_p'"!=".") {
1092
+ if ((`nbins'-1)*(`cb_p'-`cb_s'+1)+`cb_p'+1+`dfcheck_n2'>=`eN') {
1093
+ local cb_fewobs "T"
1094
+ di as text in gr "Warning: Too small effective sample size for CB."
1095
+ }
1096
+ }
1097
+ }
1098
+
1099
+ if ("`polyreg'"!="") {
1100
+ if (`polyreg'+1>=`eN') {
1101
+ local polyreg_fewobs "T"
1102
+ di as text in gr "Warning: Too small effective sample size for polynomial fit."
1103
+ }
1104
+ }
1105
+
1106
+ * Generate category variable for data and save knot in matrix
1107
+ tempname kmat
1108
+
1109
+ if ("`knotlistON'"=="T") {
1110
+ mat `kmat'=`fullkmat'
1111
+ if ("`fewobs'"=="T"&"`eN'"!="`Ndist'") {
1112
+ if (`nbins'==1) mat `kmat'=(`xmin' \ `xmax')
1113
+ else {
1114
+ binsreg_pctile `x_var' `conds' `wt', nq(`nbins') `usegtools'
1115
+ mat `kmat'=(`xmin' \ r(Q) \ `xmax')
1116
+ }
1117
+ }
1118
+ }
1119
+ else {
1120
+ if ("`fewmasspoints'"==""&("`fewobs'"!="T"|"`eN'"!="`Ndist'")) {
1121
+ if ("`pos'"=="ES") {
1122
+ local stepsize=(`xmax'-`xmin')/`nbins'
1123
+ forvalues i=1/`=`nbins'+1' {
1124
+ mat `kmat'=(nullmat(`kmat') \ `=`xmin'+`stepsize'*(`i'-1)')
1125
+ }
1126
+ }
1127
+ else {
1128
+ if (`nbins'==1) mat `kmat'=(`xmin' \ `xmax')
1129
+ else {
1130
+ binsreg_pctile `x_var' `conds' `wt', nq(`nbins') `usegtools'
1131
+ mat `kmat'=(`xmin' \ r(Q) \ `xmax')
1132
+ }
1133
+ }
1134
+ }
1135
+ }
1136
+
1137
+ * Renew knot list if few mass points
1138
+ if (("`fewobs'"=="T"&"`eN'"=="`Ndist'")|"`fewmasspoints'"!="") {
1139
+ qui tab `x_var' `conds', matrow(`kmat')
1140
+ if ("`fewmasspoints'"!="") {
1141
+ local nbins=rowsof(`kmat')
1142
+ local Ndist=`nbins'
1143
+ local eN=`Ndist'
1144
+ }
1145
+ }
1146
+ else {
1147
+ mata: st_matrix("`kmat'", (`xmin' \ uniqrows(st_matrix("`kmat'")[|2 \ `=`nbins'+1'|])))
1148
+ if (`nbins'!=rowsof(`kmat')-1) {
1149
+ di as text in gr "Warning: Repeated knots. Some bins dropped."
1150
+ local nbins=rowsof(`kmat')-1
1151
+ }
1152
+
1153
+ binsreg_irecode `x_var' `conds', knotmat(`kmat') bin(`xcat') ///
1154
+ `usegtools' nbins(`nbins') pos(`pos') knotliston(`knotlistON')
1155
+
1156
+ mata: `xcatsub'=st_data(., "`xcat'")
1157
+ if (`bynum'>1) {
1158
+ mata: `xcatsub'=select(`xcatsub', `byindex')
1159
+ }
1160
+ }
1161
+
1162
+ *************************************************
1163
+ **** Check for empty bins ***********************
1164
+ *************************************************
1165
+ mata: `binedges'=. /* initialize */
1166
+ if ("`fewobs'"!="T"&"`localcheck'"=="T") {
1167
+ mata: st_local("Ncat", strofreal(rows(uniqrows(`xcatsub'))))
1168
+ if (`nbins'==`Ncat') {
1169
+ mata: `binedges'=binsreg_uniq(`xsub', `xcatsub', `nbins', "uniqmin")
1170
+ }
1171
+ else {
1172
+ local uniqmin=0
1173
+ di as text in gr "Warning: There are empty bins. Specify a smaller number in nbins()."
1174
+ }
1175
+
1176
+ if ("`dots_p'"!=".") {
1177
+ if (`uniqmin'<`dots_p'+1) {
1178
+ local dots_fewobs "T"
1179
+ di as text in gr "Warning: Some bins have too few distinct x-values for dots."
1180
+ }
1181
+ }
1182
+ if ("`line_p'"!=".") {
1183
+ if (`uniqmin'<`line_p'+1) {
1184
+ local line_fewobs "T"
1185
+ di as text in gr "Warning: Some bins have too few distinct x-values for line."
1186
+ }
1187
+ }
1188
+ if ("`ci_p'"!=".") {
1189
+ if (`uniqmin'<`ci_p'+1) {
1190
+ local ci_fewobs "T"
1191
+ di as text in gr "Warning: Some bins have too few distinct x-values for CI."
1192
+ }
1193
+ }
1194
+ if ("`cb_p'"!=".") {
1195
+ if (`uniqmin'<`cb_p'+1) {
1196
+ local cb_fewobs "T"
1197
+ di as text in gr "Warning: Some bins have too few distinct x-values for CB."
1198
+ }
1199
+ }
1200
+ }
1201
+
1202
+ * Now, save nbins in a list !!!
1203
+ mat `nbinslist'=(nullmat(`nbinslist') \ `nbins')
1204
+
1205
+ **********************************************************
1206
+ **** Count the number of rows needed (within loop!) ******
1207
+ **********************************************************
1208
+ local byfirst=`bylast'+1
1209
+ local byrange=0
1210
+ if ("`fewobs'"!="T") {
1211
+ local dots_nr=`dotsngrid_mean'*`nbins'
1212
+ if (`dotsngrid'!=0) local dots_nr=`dots_nr'+`dotsngrid'*`nbins'+`nbins'-1
1213
+ local ci_nr=`cingrid_mean'*`nbins'
1214
+ if (`cingrid'!=0) local ci_nr=`ci_nr'+`cingrid'*`nbins'+`nbins'-1
1215
+ if (`linengrid'!=0) local line_nr=`linengrid'*`nbins'+`nbins'-1
1216
+ if (`cbngrid'!=0) local cb_nr=`cbngrid'*`nbins'+`nbins'-1
1217
+ if (`polyregngrid'!=0) {
1218
+ local poly_nr=`polyregngrid'*`nbins'+`nbins'-1
1219
+ if (`polyregcingrid'!=0) local polyci_nr=`polyregcingrid'*`nbins'+`nbins'-1
1220
+ }
1221
+ local byrange=max(`dots_nr'+0,`line_nr'+0,`ci_nr'+0,`cb_nr'+0, `poly_nr'+0, `polyci_nr'+0)
1222
+ }
1223
+ else {
1224
+ if ("`eN'"=="`Ndist'") {
1225
+ if (`polyregngrid'!=0) {
1226
+ local poly_nr=`polyregngrid'*(`nbins'-1)+`nbins'-1-1
1227
+ if (`polyregcingrid'!=0) local polyci_nr=`polyregcingrid'*(`nbins'-1)+`nbins'-1-1
1228
+ }
1229
+ }
1230
+ else {
1231
+ if (`polyregngrid'!=0) {
1232
+ local poly_nr=`polyregngrid'*`nbins'+`nbins'-1
1233
+ if (`polyregcingrid'!=0) local polyci_nr=`polyregcingrid'*`nbins'+`nbins'-1
1234
+ }
1235
+ }
1236
+ local byrange=max(`nbins', `poly_nr'+0, `polyci_nr'+0)
1237
+ }
1238
+ local bylast=`bylast'+`byrange'
1239
+ mata: `plotmatby'=J(`byrange',`ncolplot',.)
1240
+ if ("`byval'"!="noby") {
1241
+ mata: `plotmatby'[.,1]=J(`byrange',1,`byval')
1242
+ }
1243
+
1244
+ ************************************************
1245
+ **** START: prepare data for plotting***********
1246
+ ************************************************
1247
+ local plotcmdby ""
1248
+
1249
+ ********************************
1250
+ * adjust w vars
1251
+ tempname wval
1252
+ if (`nwvar'>0) {
1253
+ if (`"`at'"'==`"mean"'|`"`at'"'==`"median"') {
1254
+ matrix `wval'=J(1, `nwvar', 0)
1255
+ tempname wvaltemp mataobj
1256
+ mata: `mataobj'=.
1257
+ foreach wpos in `indexlist' {
1258
+ local wname: word `wpos' of `w_var'
1259
+ if ("`usegtools'"=="") {
1260
+ if ("`wtype'"!="") qui tabstat `wname' `conds' [aw`exp'], stat(`at') save
1261
+ else qui tabstat `wname' `conds', stat(`at') save
1262
+ mat `wvaltemp'=r(StatTotal)
1263
+ }
1264
+ else {
1265
+ qui gstats tabstat `wname' `conds' `wt', stat(`at') matasave("`mataobj'")
1266
+ mata: st_matrix("`wvaltemp'", `mataobj'.getOutputCol(1))
1267
+ }
1268
+ mat `wval'[1,`wpos']=`wvaltemp'[1,1]
1269
+ }
1270
+ mata: mata drop `mataobj'
1271
+ }
1272
+ else if (`"`at'"'==`"0"') {
1273
+ matrix `wval'=J(1,`nwvar',0)
1274
+ }
1275
+ else if ("`atwout'"=="user") {
1276
+ matrix `wval'=`wuser'
1277
+ }
1278
+ }
1279
+
1280
+
1281
+ *************************************************
1282
+ ********** dots and ci for few obs. case ********
1283
+ *************************************************
1284
+ if (`dotsntot'!=0&"`plot'"==""&"`fewobs'"=="T") {
1285
+ di as text in gr "Warning: dots(0 0) is used."
1286
+ if (`deriv'>0) di as text in gr "Warning: deriv(0 0) is used."
1287
+
1288
+ local dots_first=`byfirst'
1289
+ local dots_last=`byfirst'-1+`nbins'
1290
+
1291
+ mata: `plotmatby'[|1,`dots_start'+2 \ `nbins',`dots_start'+2|]=range(1,`nbins',1)
1292
+
1293
+ if ("`eN'"=="`Ndist'") {
1294
+ mata: `plotmatby'[|1,`dots_start' \ `nbins',`dots_start'|]=st_matrix("`kmat'"); ///
1295
+ `plotmatby'[|1,`dots_start'+1 \ `nbins',`dots_start'+1|]=J(`nbins',1,1)
1296
+
1297
+ * Renew knot commalist, each value forms a group
1298
+ local xknot ""
1299
+ forvalues i=1/`nbins' {
1300
+ local xknot `xknot' `kmat'[`i',1]
1301
+ }
1302
+ local xknotcommalist : subinstr local xknot " " ",", all
1303
+ qui replace `xcat'=1+irecode(`x_var',`xknotcommalist') `conds'
1304
+ }
1305
+ else {
1306
+ tempname grid
1307
+ mat `grid'=(`kmat'[1..`nbins',1]+`kmat'[2..`nbins'+1,1])/2
1308
+ mata: `plotmatby'[|1,`dots_start' \ `nbins',`dots_start'|]=st_matrix("`grid'"); ///
1309
+ `plotmatby'[|1,`dots_start'+1 \ `nbins',`dots_start'+1|]=J(`nbins',1,0)
1310
+ }
1311
+
1312
+ local nseries=`nbins'
1313
+ capture probit `y_var' ibn.`xcat' `w_var' `conds' `wt', nocon `vce' `probitopt'
1314
+ tempname fewobs_b fewobs_V
1315
+ if (_rc==0) {
1316
+ mat `fewobs_b'=e(b)
1317
+ mat `fewobs_V'=e(V)
1318
+ mata: binsreg_checkdrop("`fewobs_b'", "`fewobs_V'", `nseries')
1319
+ if (`nwvar'>0) {
1320
+ mat `fewobs_b'=`fewobs_b'[1,1..`nseries']+(`fewobs_b'[1,`=`nseries'+1'..`=`nseries'+`nwvar'']*`wval'')*J(1,`nseries',1)
1321
+ }
1322
+ else {
1323
+ mat `fewobs_b'=`fewobs_b'[1,1..`nseries']
1324
+ }
1325
+ }
1326
+ else {
1327
+ error _rc
1328
+ exit _rc
1329
+ }
1330
+
1331
+ if ("`transform'"=="T") {
1332
+ mata: `plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]=normal(st_matrix("`fewobs_b'"))'
1333
+ }
1334
+ else {
1335
+ mata: `plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]=st_matrix("`fewobs_b'")'
1336
+ }
1337
+
1338
+ local plotnum=`plotnum'+1
1339
+ local legendnum `legendnum' `plotnum'
1340
+ local col: word `counter_by' of `bycolors'
1341
+ local sym: word `counter_by' of `bysymbols'
1342
+ local plotcond ""
1343
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1344
+ local plotcond `plotcond' if
1345
+ if ("`plotxrange'"!="") {
1346
+ local plotcond `plotcond' dots_x>=`min_xr'
1347
+ if ("`max_xr'"!="") local plotcond `plotcond' &dots_x<=`max_xr'
1348
+ }
1349
+ if ("`plotyrange'"!="") {
1350
+ if ("`plotxrange'"=="") local plotcond `plotcond' dots_fit>=`min_yr'
1351
+ else local plotcond `plotcond' &dots_fit>=`min_yr'
1352
+ if ("`max_yr'"!="") local plotcond `plotcond' &dots_fit<=`max_yr'
1353
+ }
1354
+ }
1355
+
1356
+ local plotcmdby `plotcmdby' (scatter dots_fit dots_x ///
1357
+ `plotcond' in `dots_first'/`dots_last', ///
1358
+ mcolor(`col') msymbol(`sym') `dotsplotopt')
1359
+
1360
+ if (`cintot'!=0) {
1361
+ di as text in gr "Warning: ci(0 0) is used."
1362
+
1363
+ if (`nwvar'>0) {
1364
+ mata: `mata_se'=(I(`nseries'), J(`nseries',1,1)#st_matrix("`wval'"))
1365
+ }
1366
+ else {
1367
+ mata: `mata_se'=I(`nseries')
1368
+ }
1369
+
1370
+ mata: `plotmatby'[|1,`ci_start'+1 \ `nbins',`ci_start'+2|]=`plotmatby'[|1,`dots_start'+1 \ `nbins',`dots_start'+2|]; ///
1371
+ `mata_se'=sqrt(rowsum((`mata_se'*st_matrix("`fewobs_V'")):*`mata_se'))
1372
+ if ("`transform'"=="T") {
1373
+ mata: `mata_se'=`mata_se':*(normalden(st_matrix("`fewobs_b'"))')
1374
+ }
1375
+ mata: `plotmatby'[|1,`ci_start'+3 \ `nbins',`ci_start'+3|]=`plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]-`mata_se'*invnormal(`alpha'); ///
1376
+ `plotmatby'[|1,`ci_start'+4 \ `nbins',`ci_start'+4|]=`plotmatby'[|1,`dots_start'+3 \ `nbins',`dots_start'+3|]+`mata_se'*invnormal(`alpha')
1377
+ mata: mata drop `mata_se'
1378
+
1379
+ local plotnum=`plotnum'+1
1380
+ local lty: word `counter_by' of `bylpatterns'
1381
+ local plotcmdby `plotcmdby' (rcap CI_l CI_r dots_x ///
1382
+ `plotcond' in `dots_first'/`dots_last', ///
1383
+ sort lcolor(`col') lpattern(`lty') `ciplotopt')
1384
+ }
1385
+ }
1386
+
1387
+ *********************************************
1388
+ **** The following handles the usual case ***
1389
+ *********************************************
1390
+ * Turn on or off?
1391
+ local dotsON ""
1392
+ local lineON ""
1393
+ local polyON ""
1394
+ local ciON ""
1395
+ local cbON ""
1396
+ if (`dotsntot'!=0&"`plot'"==""&"`fewobs'"!="T"&"`dots_fewobs'"!="T") {
1397
+ local dotsON "T"
1398
+ }
1399
+ if (`linengrid'!=0&"`plot'"==""&"`line_fewobs'"!="T"&"`fewobs'"!="T") {
1400
+ local lineON "T"
1401
+ }
1402
+ if (`polyregngrid'!=0&"`plot'"==""&"`polyreg_fewobs'"!="T") {
1403
+ local polyON "T"
1404
+ }
1405
+ if (`cintot'!=0&"`plot'"==""&"`ci_fewobs'"!="T"&"`fewobs'"!="T") {
1406
+ local ciON "T"
1407
+ }
1408
+ if (`cbngrid'!=0&"`plot'"==""&"`cb_fewobs'"!="T"&"`fewobs'"!="T") {
1409
+ local cbON "T"
1410
+ }
1411
+
1412
+
1413
+ ************************
1414
+ ****** Dots ************
1415
+ ************************
1416
+ tempname xmean
1417
+
1418
+ if ("`dotsON'"=="T") {
1419
+ local dots_first=`byfirst'
1420
+ local dots_last=`byfirst'+`dots_nr'-1
1421
+
1422
+ * fitting
1423
+ tempname dots_b dots_V
1424
+ if (("`dots_p'"=="`ci_p'"&"`dots_s'"=="`ci_s'"&"`ciON'"=="T")| ///
1425
+ ("`dots_p'"=="`cb_p'"&"`dots_s'"=="`cb_s'"&"`cbON'"=="T")) {
1426
+ binsprobit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1427
+ p(`dots_p') s(`dots_s') type(dots) `vce' ///
1428
+ xcat(`xcat') kmat(`kmat') dotsmean(`dotsngrid_mean') ///
1429
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1430
+ usereg `sorted' `usegtools' probitopt(`probitopt')
1431
+ }
1432
+ else {
1433
+ binsprobit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1434
+ p(`dots_p') s(`dots_s') type(dots) `vce' ///
1435
+ xcat(`xcat') kmat(`kmat') dotsmean(`dotsngrid_mean') ///
1436
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1437
+ `sorted' `usegtools' probitopt(`probitopt')
1438
+ }
1439
+
1440
+ mat `dots_b'=e(bmat)
1441
+ mat `dots_V'=e(Vmat)
1442
+ if (`dotsngrid_mean'!=0) mat `xmean'=e(xmat)
1443
+
1444
+ * prediction
1445
+ if (`dotsngrid_mean'==0) {
1446
+ mata: `plotmatby'[|1,`dots_start' \ `dots_nr',`dots_end'|] = ///
1447
+ binsprobit_plotmat("`dots_b'", "`dots_V'", ., "`kmat'", ///
1448
+ `nbins', `dots_p', `dots_s', `deriv', ///
1449
+ "dots", `dotsngrid', "`wval'", `nwvar', ///
1450
+ "`transform'", "`asyvar'")
1451
+ }
1452
+ else {
1453
+ mata: `plotmatby'[|1,`dots_start' \ `dots_nr',`dots_end'|] = ///
1454
+ binsprobit_plotmat("`dots_b'", "`dots_V'", ., "`kmat'", ///
1455
+ `nbins', `dots_p', `dots_s', `deriv', ///
1456
+ "dots", `dotsngrid', "`wval'", `nwvar', ///
1457
+ "`transform'", "`asyvar'", "`xmean'")
1458
+ }
1459
+
1460
+ * dots
1461
+ local plotnum=`plotnum'+1
1462
+ if ("`cbON'"=="T") local legendnum `legendnum' `=`plotnum'+1'
1463
+ else {
1464
+ local legendnum `legendnum' `plotnum'
1465
+ }
1466
+ local col: word `counter_by' of `bycolors'
1467
+ local sym: word `counter_by' of `bysymbols'
1468
+ local plotcond ""
1469
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1470
+ local plotcond if
1471
+ if ("`plotxrange'"!="") {
1472
+ local plotcond `plotcond' dots_x>=`min_xr'
1473
+ if ("`max_xr'"!="") local plotcond `plotcond' &dots_x<=`max_xr'
1474
+ }
1475
+ if ("`plotyrange'"!="") {
1476
+ if ("`plotxrange'"=="") local plotcond `plotcond' dots_fit>=`min_yr'
1477
+ else local plotcond `plotcond' &dots_fit>=`min_yr'
1478
+ if ("`max_yr'"!="") local plotcond `plotcond' &dots_fit<=`max_yr'
1479
+ }
1480
+ }
1481
+
1482
+ local plotcmdby `plotcmdby' (scatter dots_fit dots_x ///
1483
+ `plotcond' in `dots_first'/`dots_last', ///
1484
+ mcolor(`col') msymbol(`sym') `dotsplotopt')
1485
+ }
1486
+
1487
+ **********************************************
1488
+ ********************* Line *******************
1489
+ **********************************************
1490
+ if ("`lineON'"=="T") {
1491
+ local line_first=`byfirst'
1492
+ local line_last=`byfirst'-1+`line_nr'
1493
+
1494
+ * fitting
1495
+ tempname line_b line_V
1496
+ capture confirm matrix `dots_b' `dots_V'
1497
+ if ("`line_p'"=="`dots_p'"& "`line_s'"=="`dots_s'" & _rc==0) {
1498
+ matrix `line_b'=`dots_b'
1499
+ matrix `line_V'=`dots_V'
1500
+ }
1501
+ else {
1502
+ if (("`line_p'"=="`ci_p'"&"`line_s'"=="`ci_s'"&"`ciON'"=="T")| ///
1503
+ ("`line_p'"=="`cb_p'"&"`line_s'"=="`cb_s'"&"`cbON'"=="T")) {
1504
+ binsprobit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1505
+ p(`line_p') s(`line_s') type(line) `vce' ///
1506
+ xcat(`xcat') kmat(`kmat') dotsmean(0) ///
1507
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1508
+ usereg `sorted' `usegtools' probitopt(`probitopt')
1509
+ }
1510
+ else {
1511
+ binsprobit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1512
+ p(`line_p') s(`line_s') type(line) `vce' ///
1513
+ xcat(`xcat') kmat(`kmat') dotsmean(0) ///
1514
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1515
+ `sorted' `usegtools' probitopt(`probitopt')
1516
+ }
1517
+ mat `line_b'=e(bmat)
1518
+ mat `line_V'=e(Vmat)
1519
+ }
1520
+
1521
+ * prediction
1522
+ mata: `plotmatby'[|1,`line_start' \ `line_nr',`line_end'|] = ///
1523
+ binsprobit_plotmat("`line_b'", "`line_V'", ., "`kmat'", ///
1524
+ `nbins', `line_p', `line_s', `deriv', ///
1525
+ "line", `linengrid', "`wval'", `nwvar', "`transform'", "`asyvar'")
1526
+
1527
+ * line
1528
+ local plotnum=`plotnum'+1
1529
+ local col: word `counter_by' of `bycolors'
1530
+ local lty: word `counter_by' of `bylpatterns'
1531
+ local plotcond ""
1532
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1533
+ local plotcond if
1534
+ if ("`plotxrange'"!="") {
1535
+ local plotcond `plotcond' line_x>=`min_xr'
1536
+ if ("`max_xr'"!="") local plotcond `plotcond' &line_x<=`max_xr'
1537
+ }
1538
+ if ("`plotyrange'"!="") {
1539
+ if ("`plotxrange'"=="") local plotcond `plotcond' line_fit>=`min_yr'
1540
+ else local plotcond `plotcond' &line_fit>=`min_yr'
1541
+ if ("`max_yr'"!="") local plotcond `plotcond' &(line_fit<=`max_yr'|line_fit==.)
1542
+ }
1543
+ }
1544
+
1545
+ local plotcmdby `plotcmdby' (line line_fit line_x ///
1546
+ `plotcond' in `line_first'/`line_last', sort cmissing(n) ///
1547
+ lcolor(`col') lpattern(`lty') `lineplotopt')
1548
+
1549
+ }
1550
+
1551
+ ***********************************
1552
+ ******* Polynomial fit ************
1553
+ ***********************************
1554
+ if ("`polyON'"=="T") {
1555
+ if (`nwvar'>0) {
1556
+ di as text "Note: When additional covariates w are included, the polynomial fit may not always be close to the binscatter fit."
1557
+ }
1558
+
1559
+ local poly_first=`byfirst'
1560
+ local poly_last=`byfirst'-1+`poly_nr'
1561
+
1562
+ mata:`plotmatby'[|1,`poly_start' \ `poly_nr',`poly_start'+2|]=binsreg_grids("`kmat'",`polyregngrid')
1563
+
1564
+ local poly_series ""
1565
+ forval i=0/`polyreg' {
1566
+ tempvar x_var_`i'
1567
+ qui gen `x_var_`i''=`x_var'^`i' `conds'
1568
+ local poly_series `poly_series' `x_var_`i''
1569
+ }
1570
+
1571
+ capture probit `y_var' `poly_series' `w_var' `conds' `wt', nocon `vce' `probitopt'
1572
+ * store results
1573
+ tempname poly_b poly_V poly_adjw
1574
+ if (_rc==0) {
1575
+ matrix `poly_b'=e(b)
1576
+ matrix `poly_V'=e(V)
1577
+ }
1578
+ else {
1579
+ error _rc
1580
+ exit _rc
1581
+ }
1582
+
1583
+ * Data for derivative
1584
+ mata: `Xm'=J(`poly_nr',0,.); `Xm0'=J(`poly_nr',0,.)
1585
+ forval i=`deriv'/`polyreg' {
1586
+ mata: `Xm'=(`Xm', ///
1587
+ `plotmatby'[|1,`poly_start' \ `poly_nr',`poly_start'|]:^(`i'-`deriv')* ///
1588
+ factorial(`i')/factorial(`i'-`deriv'))
1589
+ }
1590
+ mata: `Xm'=(J(`poly_nr', `deriv',0), `Xm')
1591
+ if (`nwvar'>0) {
1592
+ if (`deriv'==0) mata: `Xm'=(`Xm', J(`poly_nr',1,1)#st_matrix("`wval'"))
1593
+ else mata: `Xm'=(`Xm', J(`poly_nr',`nwvar',0))
1594
+ }
1595
+
1596
+ if ("`transform'"=="T") {
1597
+ if (`deriv'==0) {
1598
+ mata:`plotmatby'[|1,`poly_start'+3 \ `poly_nr',`poly_start'+3|]=normal(`Xm'*st_matrix("`poly_b'")')
1599
+ }
1600
+ else if (`deriv'==1) {
1601
+ forval i=0/`polyreg' {
1602
+ mata: `Xm0'=(`Xm0', `plotmatby'[|1,`poly_start' \ `poly_nr',`poly_start'|]:^`i')
1603
+ }
1604
+ if (`nwvar'>0) mata: `Xm0'=(`Xm0', J(`poly_nr',1,1)#st_matrix("`wval'"))
1605
+ mata:`plotmatby'[|1,`poly_start'+3 \ `poly_nr',`poly_start'+3|]=normalden(`Xm0'*st_matrix("`poly_b'")'):* ///
1606
+ (`Xm'*st_matrix("`poly_b'")')
1607
+ }
1608
+ }
1609
+ else {
1610
+ mata:`plotmatby'[|1,`poly_start'+3 \ `poly_nr',`poly_start'+3|]=`Xm'*st_matrix("`poly_b'")'
1611
+ }
1612
+
1613
+ mata: mata drop `Xm' `Xm0'
1614
+
1615
+ local plotnum=`plotnum'+1
1616
+ local col: word `counter_by' of `bycolors'
1617
+ local lty: word `counter_by' of `bylpatterns'
1618
+ local plotcond ""
1619
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1620
+ local plotcond if
1621
+ if ("`plotxrange'"!="") {
1622
+ local plotcond `plotcond' poly_x>=`min_xr'
1623
+ if ("`max_xr'"!="") local plotcond `plotcond' &poly_x<=`max_xr'
1624
+ }
1625
+ if ("`plotyrange'"!="") {
1626
+ if ("`plotxrange'"=="") local plotcond `plotcond' poly_fit>=`min_yr'
1627
+ else local plotcond `plotcond' &poly_fit>=`min_yr'
1628
+ if ("`max_yr'"!="") local plotcond `plotcond' &poly_fit<=`max_yr'
1629
+ }
1630
+ }
1631
+
1632
+ local plotcmdby `plotcmdby' (line poly_fit poly_x ///
1633
+ `plotcond' in `poly_first'/`poly_last', ///
1634
+ sort lcolor(`col') lpattern(`lty') `polyregplotopt')
1635
+
1636
+ * add CI for global poly?
1637
+ if (`polyregcingrid'!=0) {
1638
+ local polyci_first=`byfirst'
1639
+ local polyci_last=`byfirst'-1+`polyci_nr'
1640
+
1641
+ mata: `plotmatby'[|1,`polyci_start' \ `polyci_nr',`polyci_start'+2|]=binsreg_grids("`kmat'", `polyregcingrid')
1642
+
1643
+ mata: `Xm'=J(`polyci_nr',0,.); `Xm0'=J(`polyci_nr',0,.)
1644
+ forval i=`deriv'/`polyreg' {
1645
+ mata:`Xm'=(`Xm', ///
1646
+ `plotmatby'[|1,`polyci_start' \ `polyci_nr',`polyci_start'|]:^(`i'-`deriv')* ///
1647
+ factorial(`i')/factorial(`i'-`deriv'))
1648
+ }
1649
+ mata: `Xm'=(J(`polyci_nr', `deriv',0), `Xm')
1650
+ if (`nwvar'>0) {
1651
+ if (`deriv'==0) mata: `Xm'=(`Xm', J(`polyci_nr',1,1)#st_matrix("`wval'"))
1652
+ else mata: `Xm'=(`Xm', J(`polyci_nr',`nwvar',0))
1653
+ }
1654
+
1655
+ if ("`transform'"=="T") {
1656
+ if (`deriv'==0) {
1657
+ mata: `mata_fit'=normal(`Xm'*st_matrix("`poly_b'")')
1658
+ mata: `mata_se'=normalden(`Xm'*st_matrix("`poly_b'")'):* ///
1659
+ sqrt(rowsum((`Xm'*st_matrix("`poly_V'")):*`Xm'))
1660
+ }
1661
+ else if (`deriv'==1) {
1662
+ forval i=0/`polyreg' {
1663
+ mata: `Xm0'=(`Xm0', `plotmatby'[|1,`polyci_start' \ `polyci_nr',`polyci_start'|]:^`i')
1664
+ }
1665
+ if (`nwvar'>0) mata: `Xm0'=(`Xm0', J(`polyci_nr',1,1)#st_matrix("`wval'"))
1666
+ mata:`mata_fit'=normalden(`Xm0'*st_matrix("`poly_b'")'):* ///
1667
+ (`Xm'*st_matrix("`poly_b'")')
1668
+
1669
+ tempname tempobj
1670
+ mata: `tempobj'=`Xm0'*st_matrix("`poly_b'")'; ///
1671
+ `tempobj'=(-`tempobj'):*normalden(`tempobj'):*(`Xm'*st_matrix("`poly_b'")'):*`Xm0' + ///
1672
+ normalden(`tempobj'):*`Xm'; ///
1673
+ `mata_se'=sqrt(rowsum((`tempobj'*st_matrix("`poly_V'")):*`tempobj'))
1674
+ mata: mata drop `tempobj'
1675
+ }
1676
+ }
1677
+ else {
1678
+ mata: `mata_fit'=`Xm'*st_matrix("`poly_b'")'; ///
1679
+ `mata_se'=sqrt(rowsum((`Xm'*st_matrix("`poly_V'")):*`Xm'))
1680
+ }
1681
+
1682
+ mata:`plotmatby'[|1,`polyci_start'+3 \ `polyci_nr',`polyci_start'+3|]=`mata_fit'-`mata_se'*invnormal(`alpha'); ///
1683
+ `plotmatby'[|1,`polyci_start'+4 \ `polyci_nr',`polyci_start'+4|]=`mata_fit'+`mata_se'*invnormal(`alpha'); ///
1684
+ `plotmatby'[selectindex(`plotmatby'[,`=`polyci_start'+1']:==1),(`=`polyci_start'+3',`=`polyci_start'+4')]=J(`=`nbins'-1',2,.)
1685
+
1686
+ mata: mata drop `Xm' `Xm0' `mata_fit' `mata_se'
1687
+
1688
+ * poly ci
1689
+ local plotnum=`plotnum'+1
1690
+ local plotcond ""
1691
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1692
+ local plotcond if
1693
+ if ("`plotxrange'"!="") {
1694
+ local plotcond `plotcond' polyCI_x>=`min_xr'
1695
+ if ("`max_xr'"!="") local plotcond `plotcond' &polyCI_x<=`max_xr'
1696
+ }
1697
+ if ("`plotyrange'"!="") {
1698
+ if ("`plotxrange'"=="") local plotcond `plotcond' polyCI_l>=`min_yr'
1699
+ else local plotcond `plotcond' &polyCI_l>=`min_yr'
1700
+ if ("`max_yr'"!="") local plotcond `plotcond' &polyCI_r<=`max_yr'
1701
+ }
1702
+ }
1703
+
1704
+ local plotcmdby `plotcmdby' (rcap polyCI_l polyCI_r polyCI_x ///
1705
+ `plotcond' in `polyci_first'/`polyci_last', ///
1706
+ sort lcolor(`col') lpattern(`lty') `ciplotopt')
1707
+ }
1708
+ }
1709
+
1710
+
1711
+ **********************************
1712
+ ******* Confidence Interval ******
1713
+ **********************************
1714
+ if ("`ciON'"=="T") {
1715
+ local ci_first=`byfirst'
1716
+ local ci_last=`byfirst'-1+`ci_nr'
1717
+
1718
+ * fitting
1719
+ tempname ci_b ci_V
1720
+ capture confirm matrix `line_b' `line_V'
1721
+ if ("`ci_p'"=="`line_p'"& "`ci_s'"=="`line_s'" & _rc==0) {
1722
+ matrix `ci_b'=`line_b'
1723
+ matrix `ci_V'=`line_V'
1724
+ }
1725
+ else {
1726
+ capture confirm matrix `dots_b' `dots_V'
1727
+ if ("`ci_p'"=="`dots_p'"& "`ci_s'"=="`dots_s'" & _rc==0) {
1728
+ matrix `ci_b'=`dots_b'
1729
+ matrix `ci_V'=`dots_V'
1730
+ }
1731
+ }
1732
+
1733
+ capture confirm matrix `ci_b' `ci_V' `xmean'
1734
+ if (_rc!=0) {
1735
+ binsprobit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1736
+ p(`ci_p') s(`ci_s') type(ci) `vce' ///
1737
+ xcat(`xcat') kmat(`kmat') dotsmean(`cingrid_mean') ///
1738
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1739
+ `sorted' `usegtools' probitopt(`probitopt')
1740
+
1741
+ mat `ci_b'=e(bmat)
1742
+ mat `ci_V'=e(Vmat)
1743
+ mat `xmean'=e(xmat)
1744
+ }
1745
+
1746
+ * prediction
1747
+ if (`cingrid_mean'==0) {
1748
+ mata: `plotmatby'[|1,`ci_start' \ `ci_nr',`ci_end'|] = ///
1749
+ binsprobit_plotmat("`ci_b'", "`ci_V'", ///
1750
+ `=invnormal(`alpha')', "`kmat'", ///
1751
+ `nbins', `ci_p', `ci_s', `deriv', "ci", ///
1752
+ `cingrid', "`wval'", `nwvar', "`transform'", "`asyvar'")
1753
+ }
1754
+ else {
1755
+ mata: `plotmatby'[|1,`ci_start' \ `ci_nr',`ci_end'|] = ///
1756
+ binsprobit_plotmat("`ci_b'", "`ci_V'", ///
1757
+ `=invnormal(`alpha')', "`kmat'", ///
1758
+ `nbins', `ci_p', `ci_s', `deriv', "ci", ///
1759
+ `cingrid', "`wval'", `nwvar', ///
1760
+ "`transform'", "`asyvar'", "`xmean'")
1761
+ }
1762
+
1763
+ * ci
1764
+ local plotnum=`plotnum'+1
1765
+ local col: word `counter_by' of `bycolors'
1766
+ local lty: word `counter_by' of `bylpatterns'
1767
+ local plotcond ""
1768
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1769
+ local plotcond if
1770
+ if ("`plotxrange'"!="") {
1771
+ local plotcond `plotcond' CI_x>=`min_xr'
1772
+ if ("`max_xr'"!="") local plotcond `plotcond' &CI_x<=`max_xr'
1773
+ }
1774
+ if ("`plotyrange'"!="") {
1775
+ if ("`plotxrange'"=="") local plotcond `plotcond' CI_l>=`min_yr'
1776
+ else local plotcond `plotcond' &CI_l>=`min_yr'
1777
+ if ("`max_yr'"!="") local plotcond `plotcond' &CI_r<=`max_yr'
1778
+ }
1779
+ }
1780
+
1781
+ local plotcmdby `plotcmdby' (rcap CI_l CI_r CI_x ///
1782
+ `plotcond' in `ci_first'/`ci_last', ///
1783
+ sort lcolor(`col') lpattern(`lty') `ciplotopt')
1784
+
1785
+ }
1786
+
1787
+ *******************************
1788
+ ***** Confidence Band *********
1789
+ *******************************
1790
+ tempname cval
1791
+ scalar `cval'=.
1792
+ if ("`cbON'"=="T") {
1793
+ if (`nsims'<2000|`simsgrid'<50) {
1794
+ di as text "Note: A larger number random draws/evaluation points is recommended to obtain the final results."
1795
+ }
1796
+ * Prepare grid for plotting
1797
+ local cb_first=`byfirst'
1798
+ local cb_last=`byfirst'-1+`cb_nr'
1799
+
1800
+ * fitting
1801
+ tempname cb_b cb_V
1802
+ capture confirm matrix `ci_b' `ci_V'
1803
+ if ("`cb_p'"=="`ci_p'"& "`cb_s'"=="`ci_s'" & _rc==0) {
1804
+ matrix `cb_b'=`ci_b'
1805
+ matrix `cb_V'=`ci_V'
1806
+ }
1807
+ else {
1808
+ capture confirm matrix `line_b' `line_V'
1809
+ if ("`cb_p'"=="`line_p'"& "`cb_s'"=="`line_s'" & _rc==0) {
1810
+ matrix `cb_b'=`line_b'
1811
+ matrix `cb_V'=`line_V'
1812
+ }
1813
+ else {
1814
+ capture confirm matrix `dots_b' `dots_V'
1815
+ if ("`cb_p'"=="`dots_p'"& "`cb_s'"=="`dots_s'" & _rc==0) {
1816
+ matrix `cb_b'=`dots_b'
1817
+ matrix `cb_V'=`dots_V'
1818
+ }
1819
+ else {
1820
+ binsprobit_fit `y_var' `x_var' `w_var' `conds' `wt', deriv(`deriv') ///
1821
+ p(`cb_p') s(`cb_s') type(cb) `vce' ///
1822
+ xcat(`xcat') kmat(`kmat') dotsmean(0) ///
1823
+ xname(`xsub') yname(`ysub') catname(`xcatsub') edge(`binedges') ///
1824
+ `sorted' `usegtools' probitopt(`probitopt')
1825
+ mat `cb_b'=e(bmat)
1826
+ mat `cb_V'=e(Vmat)
1827
+ }
1828
+ }
1829
+ }
1830
+
1831
+ * Compute critical values
1832
+ * Prepare grid for simulation
1833
+ local uni_last=`simsngrid'*`nbins'+`nbins'-1
1834
+ local nseries=(`cb_p'-`cb_s'+1)*(`nbins'-1)+`cb_p'+1
1835
+
1836
+ tempname cb_basis
1837
+ mata: `cb_basis'=binsreg_grids("`kmat'", `simsngrid'); ///
1838
+ `cb_basis'=binsreg_spdes(`cb_basis'[,1], "`kmat'", `cb_basis'[,3], `cb_p', `deriv', `cb_s'); ///
1839
+ `Xm'=binsreg_pred(`cb_basis', st_matrix("`cb_b'")[|1 \ `nseries'|]', ///
1840
+ st_matrix("`cb_V'")[|1,1 \ `nseries',`nseries'|], "all"); ///
1841
+ binsreg_pval(`cb_basis', `Xm'[,2], "`cb_V'", ".", `nsims', `nseries', "two", `=`level'/100', ".", "`cval'", "inf")
1842
+ mata: mata drop `cb_basis' `Xm'
1843
+
1844
+ * prediction
1845
+ mata: `plotmatby'[|1,`cb_start' \ `cb_nr',`cb_end'|] = ///
1846
+ binsprobit_plotmat("`cb_b'", "`cb_V'", ///
1847
+ `=`cval'', "`kmat'", ///
1848
+ `nbins', `cb_p', `cb_s', `deriv', ///
1849
+ "cb", `cbngrid', "`wval'", `nwvar', ///
1850
+ "`transform'", "`asyvar'")
1851
+
1852
+ * cb
1853
+ local plotnum=`plotnum'+1
1854
+ local col: word `counter_by' of `bycolors'
1855
+ local plotcond ""
1856
+ if ("`plotxrange'"!=""|"`plotyrange'"!="") {
1857
+ local plotcond if
1858
+ if ("`plotxrange'"!="") {
1859
+ local plotcond `plotcond' CB_x>=`min_xr'
1860
+ if ("`max_xr'"!="") local plotcond `plotcond' &CB_x<=`max_xr'
1861
+ }
1862
+ if ("`plotyrange'"!="") {
1863
+ if ("`plotxrange'"=="") local plotcond `plotcond' CB_l>=`min_yr'
1864
+ else local plotcond `plotcond' &CB_l>=`min_yr'
1865
+ if ("`max_yr'"!="") local plotcond `plotcond' &(CB_r<=`max_yr'|CB_r==.)
1866
+ }
1867
+ }
1868
+
1869
+ local plotcmdby (rarea CB_l CB_r CB_x ///
1870
+ `plotcond' in `cb_first'/`cb_last', sort cmissing(n) ///
1871
+ lcolor(none%0) fcolor(`col'%50) fintensity(50) `cbplotopt') `plotcmdby'
1872
+ }
1873
+ mat `cvallist'=(nullmat(`cvallist') \ `cval')
1874
+
1875
+ local plotcmd `plotcmd' `plotcmdby'
1876
+ mata: `plotmat'=(`plotmat' \ `plotmatby')
1877
+
1878
+ *********************************
1879
+ **** display ********************
1880
+ *********************************
1881
+ di ""
1882
+ * Plotting
1883
+ if ("`plot'"=="") {
1884
+ if (`counter_by'==1) {
1885
+ di in smcl in gr "Binscatter plot, probit model"
1886
+ di in smcl in gr "Bin selection method: `binselectmethod'"
1887
+ di in smcl in gr "Placement: `placement'"
1888
+ di in smcl in gr "Derivative: `deriv'"
1889
+ if (`"`savedata'"'!=`""') {
1890
+ di in smcl in gr `"Output file: `savedata'.dta"'
1891
+ }
1892
+ }
1893
+ di ""
1894
+ if ("`by'"!="") {
1895
+ di in smcl in gr "Group: `byvarname' = " in yellow "`byvalname'"
1896
+ }
1897
+ di in smcl in gr "{hline 30}{c TT}{hline 15}"
1898
+ di in smcl in gr "{lalign 1:# of observations}" _col(30) " {c |} " _col(32) as result %7.0f `N'
1899
+ di in smcl in gr "{lalign 1:# of distinct values}" _col(30) " {c |} " _col(32) as result %7.0f `Ndist'
1900
+ di in smcl in gr "{lalign 1:# of clusters}" _col(30) " {c |} " _col(32) as result %7.0f `Nclust'
1901
+ di in smcl in gr "{hline 30}{c +}{hline 15}"
1902
+ di in smcl in gr "{lalign 1:Bin/Degree selection:}" _col(30) " {c |} "
1903
+ if ("`selection'"=="P") {
1904
+ di in smcl in gr "{ralign 29:Degree of polynomial}" _col(30) " {c |} " _col(32) as result %7.0f `binsp'
1905
+ di in smcl in gr "{ralign 29:# of smoothness constraints}" _col(30) " {c |} " _col(32) as result %7.0f `binss'
1906
+ }
1907
+ else {
1908
+ di in smcl in gr "{ralign 29:Degree of polynomial}" _col(30) " {c |} " _col(32) as result %7.0f `dots_p'
1909
+ di in smcl in gr "{ralign 29:# of smoothness constraints}" _col(30) " {c |} " _col(32) as result %7.0f `dots_s'
1910
+ }
1911
+ di in smcl in gr "{ralign 29:# of bins}" _col(30) " {c |} " _col(32) as result %7.0f `nbins'
1912
+ if ("`binselectmethod'"!="User-specified") {
1913
+ if ("`binsmethod'"=="ROT") {
1914
+ di in smcl in gr "{ralign 29:imse, bias^2}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_bsq_rot'[`counter_by',1]'
1915
+ di in smcl in gr "{ralign 29:imse, var.}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_var_rot'[`counter_by',1]'
1916
+ }
1917
+ else if ("`binsmethod'"=="DPI") {
1918
+ di in smcl in gr "{ralign 29:imse, bias^2}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_bsq_dpi'[`counter_by',1]'
1919
+ di in smcl in gr "{ralign 29:imse, var.}" _col(30) " {c |} " _col(32) as result %7.3f `=`mat_imse_var_dpi'[`counter_by',1]'
1920
+ }
1921
+ }
1922
+ di in smcl in gr "{hline 30}{c BT}{hline 15}"
1923
+ di ""
1924
+ di in smcl in gr "{hline 9}{c TT}{hline 30}"
1925
+ di in smcl _col(10) "{c |}" in gr _col(17) "p" _col(25) "s" _col(33) "df"
1926
+ di in smcl in gr "{hline 9}{c +}{hline 30}"
1927
+ if (`dotsntot'!=0) {
1928
+ local dots_df=(`dots_p'-`dots_s'+1)*(`nbins'-1)+`dots_p'+1
1929
+ di in smcl in gr "{lalign 1: dots}" _col(10) "{c |}" in gr _col(17) "`dots_p'" _col(25) "`dots_s'" _col(33) "`dots_df'"
1930
+ }
1931
+ if ("`lineON'"=="T") {
1932
+ local line_df=(`line_p'-`line_s'+1)*(`nbins'-1)+`line_p'+1
1933
+ di in smcl in gr "{lalign 1: line}" _col(10) "{c |}" in gr _col(17) "`line_p'" _col(25) "`line_s'" _col(33) "`line_df'"
1934
+ }
1935
+ if (`cintot'!=0) {
1936
+ local ci_df=(`ci_p'-`ci_s'+1)*(`nbins'-1)+`ci_p'+1
1937
+ di in smcl in gr "{lalign 1: CI}" _col(10) "{c |}" in gr _col(17) "`ci_p'" _col(25) "`ci_s'" _col(33) "`ci_df'"
1938
+ }
1939
+ if ("`cbON'"=="T") {
1940
+ local cb_df=(`cb_p'-`cb_s'+1)*(`nbins'-1)+`cb_p'+1
1941
+ di in smcl in gr "{lalign 1: CB}" _col(10) "{c |}" in gr _col(17) "`cb_p'" _col(25) "`cb_s'" _col(33) "`cb_df'"
1942
+ }
1943
+ if ("`polyON'"=="T") {
1944
+ local poly_df=`polyreg'+1
1945
+ di in smcl in gr "{lalign 1: polyreg}" _col(10) "{c |}" in gr _col(17) "`polyreg'" _col(25) "NA" _col(33) "`poly_df'"
1946
+ }
1947
+ di in smcl in gr "{hline 9}{c BT}{hline 30}"
1948
+ }
1949
+
1950
+
1951
+ mata: mata drop `plotmatby'
1952
+ local ++counter_by
1953
+ }
1954
+ mata: mata drop `xsub' `ysub' `binedges'
1955
+ if (`bynum'>1) mata: mata drop `byindex'
1956
+ capture mata: mata drop `xcatsub'
1957
+ ****************** END loop ****************************************
1958
+ ********************************************************************
1959
+
1960
+
1961
+
1962
+ *******************************************
1963
+ *************** Plotting ******************
1964
+ *******************************************
1965
+ clear
1966
+ if ("`plotcmd'"!="") {
1967
+ * put data back to STATA
1968
+ mata: st_local("nr", strofreal(rows(`plotmat')))
1969
+ qui set obs `nr'
1970
+
1971
+ * MAKE SURE the orderings match
1972
+ qui gen group=. in 1
1973
+ if (`dotsntot'!=0) {
1974
+ qui gen dots_x=. in 1
1975
+ qui gen dots_isknot=. in 1
1976
+ qui gen dots_binid=. in 1
1977
+ qui gen dots_fit=. in 1
1978
+ }
1979
+ if (`linengrid'!=0&"`fullfewobs'"=="") {
1980
+ qui gen line_x=. in 1
1981
+ qui gen line_isknot=. in 1
1982
+ qui gen line_binid=. in 1
1983
+ qui gen line_fit=. in 1
1984
+ }
1985
+ if (`polyregngrid'!=0) {
1986
+ qui gen poly_x=. in 1
1987
+ qui gen poly_isknot=. in 1
1988
+ qui gen poly_binid=. in 1
1989
+ qui gen poly_fit=. in 1
1990
+ if (`polyregcingrid'!=0) {
1991
+ qui gen polyCI_x=. in 1
1992
+ qui gen polyCI_isknot=. in 1
1993
+ qui gen polyCI_binid=. in 1
1994
+ qui gen polyCI_l=. in 1
1995
+ qui gen polyCI_r=. in 1
1996
+ }
1997
+ }
1998
+ if (`cintot'!=0) {
1999
+ qui gen CI_x=. in 1
2000
+ qui gen CI_isknot=. in 1
2001
+ qui gen CI_binid=. in 1
2002
+ qui gen CI_l=. in 1
2003
+ qui gen CI_r=. in 1
2004
+ }
2005
+ if (`cbngrid'!=0&"`fullfewobs'"=="") {
2006
+ qui gen CB_x=. in 1
2007
+ qui gen CB_isknot=. in 1
2008
+ qui gen CB_binid=. in 1
2009
+ qui gen CB_l=. in 1
2010
+ qui gen CB_r=. in 1
2011
+ }
2012
+
2013
+ mata: st_store(.,.,`plotmat')
2014
+
2015
+ * Legend
2016
+ local plot_legend legend(order(
2017
+ if ("`by'"!=""&`dotsntot'!=0) {
2018
+ forval i=1/`bynum' {
2019
+ local byvalname: word `i' of `byvalnamelist'
2020
+ local plot_legend `plot_legend' `: word `i' of `legendnum'' "`byvarname'=`byvalname'"
2021
+ }
2022
+ local plot_legend `plot_legend' ))
2023
+ }
2024
+ else {
2025
+ local plot_legend legend(off)
2026
+ }
2027
+
2028
+ * Plot it
2029
+ local graphcmd twoway `plotcmd', xtitle(`x_varname') ytitle(`y_varname') xscale(range(`xsc')) `plot_legend' `options'
2030
+ `graphcmd'
2031
+ }
2032
+ mata: mata drop `plotmat' `xvec' `yvec' `byvec' `cluvec'
2033
+
2034
+
2035
+ * Save graph data ?
2036
+ * In the normal case
2037
+ if (`"`savedata'"'!=`""'&`"`plotcmd'"'!=`""') {
2038
+ * Add labels
2039
+ if ("`by'"!="") {
2040
+ if ("`bystring'"=="T") {
2041
+ label val group `bylabel'
2042
+ decode group, gen(`byvarname')
2043
+ }
2044
+ else {
2045
+ qui gen `byvarname'=group
2046
+ if ("`bylabel'"!="") label val `byvarname' `bylabel'
2047
+ }
2048
+ label var `byvarname' "Group"
2049
+ qui drop group
2050
+ order `byvarname'
2051
+ }
2052
+ else qui drop group
2053
+
2054
+ capture confirm variable dots_x dots_binid dots_isknot dots_fit
2055
+ if (_rc==0) {
2056
+ label var dots_x "Dots: grid"
2057
+ label var dots_binid "Dots: indicator of bins"
2058
+ label var dots_isknot "Dots: indicator of inner knot"
2059
+ label var dots_fit "Dots: fitted values"
2060
+ }
2061
+ capture confirm variable line_x line_binid line_isknot line_fit
2062
+ if (_rc==0) {
2063
+ label var line_x "Line: grid"
2064
+ label var line_binid "Line: indicator of bins"
2065
+ label var line_isknot "Line: indicator of inner knot"
2066
+ label var line_fit "Line: fitted values"
2067
+ }
2068
+ capture confirm variable poly_x poly_binid poly_isknot poly_fit
2069
+ if (_rc==0) {
2070
+ label var poly_x "Poly: grid"
2071
+ label var poly_binid "Poly: indicator of bins"
2072
+ label var poly_isknot "Poly: indicator of inner knot"
2073
+ label var poly_fit "Poly: fitted values"
2074
+ }
2075
+ capture confirm variable polyCI_x polyCI_binid polyCI_isknot polyCI_l polyCI_r
2076
+ if (_rc==0) {
2077
+ label var polyCI_x "Poly confidence interval: grid"
2078
+ label var polyCI_binid "Poly confidence interval: indicator of bins"
2079
+ label var polyCI_isknot "Poly confidence interval: indicator of inner knot"
2080
+ label var polyCI_l "Poly confidence interval: left boundary"
2081
+ label var polyCI_r "Poly confidence interval: right boundary"
2082
+ }
2083
+ capture confirm variable CI_x CI_binid CI_isknot CI_l CI_r
2084
+ if (_rc==0) {
2085
+ label var CI_x "Confidence interval: grid"
2086
+ label var CI_binid "Confidence interval: indicator of bins"
2087
+ label var CI_isknot "Confidence interval: indicator of inner knot"
2088
+ label var CI_l "Confidence interval: left boundary"
2089
+ label var CI_r "Confidence interval: right boundary"
2090
+ }
2091
+ capture confirm variable CB_x CB_binid CB_isknot CB_l CB_r
2092
+ if (_rc==0) {
2093
+ label var CB_x "Confidence band: grid"
2094
+ label var CB_binid "Confidence band: indicator of bins"
2095
+ label var CB_isknot "Confidence band: indicator of inner knot"
2096
+ label var CB_l "Confidence band: left boundary"
2097
+ label var CB_r "Confidence band: right boundary"
2098
+ }
2099
+ qui save `"`savedata'"', `replace'
2100
+ }
2101
+ ***************************************************************************
2102
+
2103
+ *********************************
2104
+ ********** Return ***************
2105
+ *********************************
2106
+ ereturn clear
2107
+ * # of observations
2108
+ ereturn scalar N=`Ntotal'
2109
+ * Options
2110
+ ereturn scalar level=`level'
2111
+ ereturn scalar dots_p=`dots_p'
2112
+ ereturn scalar dots_s=`dots_s'
2113
+ ereturn scalar line_p=`line_p'
2114
+ ereturn scalar line_s=`line_s'
2115
+ ereturn scalar ci_p=`ci_p'
2116
+ ereturn scalar ci_s=`ci_s'
2117
+ ereturn scalar cb_p=`cb_p'
2118
+ ereturn scalar cb_s=`cb_s'
2119
+ * by group:
2120
+ *ereturn matrix knot=`kmat'
2121
+ ereturn matrix cval_by=`cvallist'
2122
+ ereturn matrix nbins_by=`nbinslist'
2123
+ ereturn matrix Nclust_by=`Nclustlist'
2124
+ ereturn matrix Ndist_by=`Ndistlist'
2125
+ ereturn matrix N_by=`Nlist'
2126
+
2127
+ ereturn matrix imse_var_rot=`mat_imse_var_rot'
2128
+ ereturn matrix imse_bsq_rot=`mat_imse_bsq_rot'
2129
+ ereturn matrix imse_var_dpi=`mat_imse_var_dpi'
2130
+ ereturn matrix imse_bsq_dpi=`mat_imse_bsq_dpi'
2131
+ end
2132
+
2133
+ * Helper commands
2134
+ * Estimation
2135
+ program define binsprobit_fit, eclass
2136
+ version 13
2137
+ syntax varlist(min=2 numeric ts fv) [if] [in] [fw aw pw] [, deriv(integer 0) ///
2138
+ p(integer 0) s(integer 0) type(string) vce(passthru) ///
2139
+ xcat(varname numeric) kmat(name) dotsmean(integer 0) /// /* xmean: report x-mean? */
2140
+ xname(name) yname(name) catname(name) edge(name) ///
2141
+ usereg sorted usegtools probitopt(string asis)] /* usereg: force the command to use reg; sored: sorted data? */
2142
+
2143
+ preserve
2144
+ marksample touse
2145
+ qui keep if `touse'
2146
+
2147
+ if ("`weight'"!="") local wt [`weight'`exp']
2148
+
2149
+ tokenize `varlist'
2150
+ local y_var `1'
2151
+ local x_var `2'
2152
+ macro shift 2
2153
+ local w_var "`*'"
2154
+ local nbins=rowsof(`kmat')-1
2155
+
2156
+ tempname matxmean temp_b temp_V
2157
+ mat `matxmean'=.
2158
+ mat `temp_b'=.
2159
+ mat `temp_V'=.
2160
+
2161
+ if (`dotsmean'!=0) {
2162
+ if ("`sorted'"==""|"`weight'"!=""|"`usegtools'"!="") {
2163
+ if ("`usegtools'"=="") {
2164
+ tempfile tmpfile
2165
+ qui save `tmpfile', replace
2166
+
2167
+ collapse (mean) `x_var' `wt', by(`xcat') fast
2168
+ mkmat `xcat' `x_var', matrix(`matxmean')
2169
+
2170
+ use `tmpfile', clear
2171
+ }
2172
+ else {
2173
+ tempname obj
2174
+ qui gstats tabstat `x_var' `wt', stats(mean) by(`xcat') matasave("`obj'")
2175
+ mata: st_matrix("`matxmean'", (`obj'.getnum(.,1), `obj'.getOutputVar("`x_var'")))
2176
+ mata: mata drop `obj'
2177
+ }
2178
+ }
2179
+ else {
2180
+ tempname output
2181
+ mata: `output'=binsreg_stat(`xname', `catname', `nbins', `edge', "mean", -1); ///
2182
+ st_matrix("`matxmean'", `output')
2183
+ mata: mata drop `output'
2184
+ }
2185
+ }
2186
+
2187
+ * Regression?
2188
+ if (`p'==0) {
2189
+ capture probit `y_var' ibn.`xcat' `w_var' `wt', nocon `vce' `probitopt'
2190
+ if (_rc==0) {
2191
+ matrix `temp_b'=e(b)
2192
+ matrix `temp_V'=e(V)
2193
+ }
2194
+ else {
2195
+ error _rc
2196
+ exit _rc
2197
+ }
2198
+ }
2199
+ else {
2200
+ local nseries=(`p'-`s'+1)*(`nbins'-1)+`p'+1
2201
+ local series ""
2202
+ forvalues i=1/`nseries' {
2203
+ tempvar sp`i'
2204
+ local series `series' `sp`i''
2205
+ qui gen `sp`i''=. in 1
2206
+ }
2207
+
2208
+ mata: binsreg_st_spdes(`xname', "`series'", "`kmat'", `catname', `p', 0, `s')
2209
+
2210
+ capture probit `y_var' `series' `w_var' `wt', nocon `vce' `probitopt'
2211
+ * store results
2212
+ if (_rc==0) {
2213
+ matrix `temp_b'=e(b)
2214
+ matrix `temp_V'=e(V)
2215
+ mata: binsreg_checkdrop("`temp_b'", "`temp_V'", `nseries')
2216
+ }
2217
+ else {
2218
+ error _rc
2219
+ exit _rc
2220
+ }
2221
+ }
2222
+
2223
+
2224
+ ereturn clear
2225
+ ereturn matrix bmat=`temp_b'
2226
+ ereturn matrix Vmat=`temp_V'
2227
+ ereturn matrix xmat=`matxmean' /* xcat, xbar */
2228
+ end
2229
+
2230
+ mata:
2231
+
2232
+ // Prediction for plotting
2233
+ real matrix binsprobit_plotmat(string scalar eb, string scalar eV, real scalar cval, ///
2234
+ string scalar knotname, real scalar J, ///
2235
+ real scalar p, real scalar s, real scalar deriv, ///
2236
+ string scalar type, real scalar ngrid, string scalar muwmat, ///
2237
+ real scalar nw, string scalar transform, string scalar avar, | string scalar muxmat)
2238
+ {
2239
+ real matrix coef, bmat, rmat, vmat, knot, xmean, wval, eval, out, fit, fit0, se, semat, Xm, Xm0, result
2240
+ real scalar nseries
2241
+
2242
+ nseries=(p-s+1)*(J-1)+p+1
2243
+ coef=st_matrix(eb)'
2244
+ bmat=coef[|1\nseries|]
2245
+ if (nw>0) rmat=coef[|(nseries+1)\rows(coef)|]
2246
+
2247
+ if (type=="ci"|type=="cb") {
2248
+ vfull=st_matrix(eV)
2249
+ vmat=vfull[|1,1\nseries,nseries|]
2250
+ }
2251
+
2252
+ // Prepare evaluation points
2253
+ eval=J(0,3,.)
2254
+ if (args()==15) {
2255
+ xmean=st_matrix(muxmat)
2256
+ eval=(eval \ (xmean[,2], J(J, 1, 0), xmean[,1]))
2257
+ }
2258
+ if (ngrid!=0) eval=(eval \ binsreg_grids(knotname, ngrid))
2259
+
2260
+ // adjust w variables
2261
+ if (nw>0) {
2262
+ wvec=st_matrix(muwmat)
2263
+ wval=wvec*rmat
2264
+ }
2265
+ else wval=0
2266
+
2267
+ fit=J(0,1,.)
2268
+ se=J(0,1,.)
2269
+ if (p==0) {
2270
+ if (args()==15) fit=(fit \ bmat)
2271
+ if (ngrid!=0) {
2272
+ fit=(fit \ (bmat#(J(ngrid,1,1)\.)))
2273
+ fit=fit[|1 \ (rows(fit)-1)|]
2274
+ }
2275
+ if (type=="ci"|type=="cb") {
2276
+ if (avar=="on") semat=sqrt(diagonal(vmat))
2277
+ else {
2278
+ if (nw>0) {
2279
+ Xm=(I(nseries), J(nseries,1,1)#wvec)
2280
+ semat=sqrt(rowsum((Xm*vfull):*Xm))
2281
+ }
2282
+ else semat=sqrt(diagonal(vmat))
2283
+ }
2284
+ if (args()==15) se=(se \ semat)
2285
+ if (ngrid!=0) {
2286
+ se=(se \ (semat#(J(ngrid,1,1)\.)))
2287
+ se=se[|1 \ (rows(se)-1)|]
2288
+ }
2289
+ }
2290
+ if (type=="dots"|type=="line") {
2291
+ if (transform=="T") out=(eval, normal(fit:+wval))
2292
+ else out=(eval, fit:+wval)
2293
+ }
2294
+ else {
2295
+ if (transform=="T") out=(eval, normal(fit:+wval)-(normalden(fit:+wval):*se)*cval, ///
2296
+ normal(fit:+wval)+(normalden(fit:+wval):*se)*cval)
2297
+ else out=(eval, (fit:+wval)-se*cval, (fit:+wval)+se*cval)
2298
+ }
2299
+ }
2300
+ else {
2301
+ Xm=binsreg_spdes(eval[,1], knotname, eval[,3], p, deriv, s)
2302
+ if (type=="dots"|type=="line") {
2303
+ if (transform=="T") {
2304
+ fit=binsreg_pred(Xm, bmat, ., "xb")[,1]
2305
+ if (deriv==0) {
2306
+ fit=normal(fit:+wval)
2307
+ }
2308
+ if (deriv==1) {
2309
+ Xm0=binsreg_spdes(eval[,1], knotname, eval[,3], p, 0, s)
2310
+ fit0=binsreg_pred(Xm0, bmat, ., "xb")[,1]
2311
+ fit=normalden(fit0:+wval):*fit
2312
+ }
2313
+
2314
+ out=(eval, fit)
2315
+ }
2316
+ else {
2317
+ fit=binsreg_pred(Xm, bmat, ., "xb")[,1]
2318
+ if (deriv==0) out=(eval, fit:+wval)
2319
+ else out=(eval, fit)
2320
+ }
2321
+ }
2322
+ else {
2323
+ if (avar=="on") {
2324
+ result=binsreg_pred(Xm, bmat, vmat, "all")
2325
+ if (transform=="T") {
2326
+ Xm0=binsreg_spdes(eval[,1], knotname, eval[,3], p, 0, s)
2327
+ fit0=binsreg_pred(Xm0, bmat, ., "xb")[,1]
2328
+ result[,2]=normalden(fit0:+wval):*result[,2]
2329
+
2330
+ if (deriv==0) {
2331
+ result[,1]=normal(result[,1]:+wval)
2332
+ }
2333
+ if (deriv==1) {
2334
+ result[,1]=normalden(fit0:+wval):*result[,1]
2335
+ }
2336
+
2337
+ out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2338
+ }
2339
+ else {
2340
+ if (deriv==0) out=(eval, (result[,1]:+wval)-cval*result[,2], (result[,1]:+wval)+cval*result[,2])
2341
+ else out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2342
+ }
2343
+ }
2344
+ else {
2345
+ result=binsreg_pred(Xm, bmat, vmat, "all")
2346
+ if (transform=="T") {
2347
+ if (deriv==0) {
2348
+ if (nw>0) Xm=(Xm, J(rows(Xm),1,1)#wvec)
2349
+ result[,2]=normalden(result[,1]:+wval):*sqrt(rowsum((Xm*vfull):*Xm))
2350
+ result[,1]=normal(result[,1]:+wval)
2351
+ }
2352
+ if (deriv==1) {
2353
+ Xm0=binsreg_spdes(eval[,1], knotname, eval[,3], p, 0, s)
2354
+ if (nw>0) {
2355
+ Xm0=(Xm0, J(rows(Xm0),1,1)#wvec)
2356
+ Xm=(Xm, J(rows(Xm),nw,0))
2357
+ }
2358
+ fit0=binsreg_pred(Xm0, coef, ., "xb")[,1]
2359
+ Xm=(-fit0):*normalden(fit0):*result[,1]:*Xm0 + ///
2360
+ normalden(fit0):*Xm
2361
+ result[,2]=sqrt(rowsum((Xm*vfull):*Xm))
2362
+ result[,1]=normalden(fit0):*result[,1]
2363
+ }
2364
+ out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2365
+ }
2366
+ else {
2367
+ if (nw>0) {
2368
+ if (deriv==0) Xm=(Xm, J(rows(Xm),1,1)#wvec)
2369
+ else Xm=(Xm, J(rows(Xm),nw,0))
2370
+ }
2371
+ result=binsreg_pred(Xm, coef, vfull, "all")
2372
+ out=(eval, result[,1]-cval*result[,2], result[,1]+cval*result[,2])
2373
+ }
2374
+ }
2375
+ }
2376
+ }
2377
+
2378
+ if (type=="dots"|(type=="line"&(s==0|s-deriv<=0))) {
2379
+ out[selectindex(out[,2]:==1),4]=J(sum(out[,2]),1,.)
2380
+ }
2381
+ if (type=="ci"|(type=="cb"&(s==0|s-deriv<=0))) {
2382
+ out[selectindex(out[,2]:==1),4..5]=J(sum(out[,2]),2,.)
2383
+ }
2384
+
2385
+ return(out)
2386
+ }
2387
+
2388
+
2389
+ end
2390
+
110/replication_package/replication/ado/plus/b/binsprobit.sthlp ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {smcl}
2
+ {* *! version 1.2 09-OCT-2022}{...}
3
+ {viewerjumpto "Syntax" "binsprobit##syntax"}{...}
4
+ {viewerjumpto "Description" "binsprobit##description"}{...}
5
+ {viewerjumpto "Options" "binsprobit##options"}{...}
6
+ {viewerjumpto "Examples" "binsprobit##examples"}{...}
7
+ {viewerjumpto "Stored results" "binsprobit##stored_results"}{...}
8
+ {viewerjumpto "References" "binsprobit##references"}{...}
9
+ {viewerjumpto "Authors" "binsprobit##authors"}{...}
10
+ {cmd:help binsprobit}
11
+ {hline}
12
+
13
+ {title:Title}
14
+
15
+ {p 4 8}{hi:binsprobit} {hline 2} Data-Driven Binscatter Probit Estimation with Robust Inference Procedures and Plots.{p_end}
16
+
17
+
18
+ {marker syntax}{...}
19
+ {title:Syntax}
20
+
21
+ {p 4 15} {cmdab:binsprobit} {depvar} {it:indvar} [{it:othercovs}] {ifin} {weight} [ {cmd:,} {opt deriv(v)} {opt at(position)} {opt nolink}{p_end}
22
+ {p 15 15} {opt dots(dotsopt)} {opt dotsgrid(dotsgridoption)} {opt dotsplotopt(dotsoption)}{p_end}
23
+ {p 15 15} {opt line(lineopt)} {opt linegrid(#)} {opt lineplotopt(lineoption)}{p_end}
24
+ {p 15 15} {opt ci(ciopt)} {opt cigrid(cigridoption)} {opt ciplotopt(rcapoption)}{p_end}
25
+ {p 15 15} {opt cb(cbopt)} {opt cbgrid(#)} {opt cbplotopt(rareaoption)}{p_end}
26
+ {p 15 15} {opt polyreg(p)} {opt polyreggrid(#)} {opt polyregcigrid(#)} {opt polyregplotopt(lineoption)}{p_end}
27
+ {p 15 15} {opth by(varname)} {cmd:bycolors(}{it:{help colorstyle}list}{cmd:)} {cmd:bysymbols(}{it:{help symbolstyle}list}{cmd:)} {cmd:bylpatterns(}{it:{help linepatternstyle}list}{cmd:)}{p_end}
28
+ {p 15 15} {opt nbins(nbinsopt)} {opt binspos(position)} {opt binsmethod(method)} {opt nbinsrot(#)} {opt samebinsby} {opt randcut(#)}{p_end}
29
+ {p 15 15} {cmd:pselect(}{it:{help numlist}}{cmd:)} {cmd:sselect(}{it:{help numlist}}{cmd:)}{p_end}
30
+ {p 15 15} {opt nsims(#)} {opt simsgrid(#)} {opt simsseed(seed)}{p_end}
31
+ {p 15 15} {opt dfcheck(n1 n2)} {opt masspoints(masspointsoption)}{p_end}
32
+ {p 15 15} {cmd:vce(}{it:{help vcetype}}{cmd:)} {opt asyvar(on/off)}{p_end}
33
+ {p 15 15} {opt level(level)} {opt probitopt(probit_option)} {opt usegtools(on/off)} {opt noplot} {opt savedata(filename)} {opt replace}{p_end}
34
+ {p 15 15} {opt plotxrange(min max)} {opt plotyrange(min max)} {it:{help twoway_options}} ]{p_end}
35
+
36
+ {p 4 8} where {depvar} is the dependent variable, {it:indvar} is the independent variable for binning, and {it:othercovs} are other covariates to be controlled for.{p_end}
37
+
38
+ {p 4 8} The degree of the piecewise polynomial p, the number of smoothness constraints s, and the derivative order v are integers
39
+ satisfying 0 <= s,v <= p, which can take different values in each case.{p_end}
40
+
41
+ {p 4 8} {opt fweight}s and {opt pweight}s are allowed; see {help weight}.{p_end}
42
+
43
+ {marker description}{...}
44
+ {title:Description}
45
+
46
+ {p 4 8} {cmd:binsprobit} implements binscatter probit estimation with robust inference procedures and plots, following the results in
47
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Binscatter.pdf":Cattaneo, Crump, Farrell and Feng (2022a)}.
48
+ Binscatter provides a flexible way to describe the mean relationship between two variables, after possibly adjusting for other covariates,
49
+ based on partitioning/binning of the independent variable of interest.
50
+ The main purpose of this command is to generate binned scatter plots with curve estimation with robust pointwise confidence intervals and uniform confidence band.
51
+ If the binning scheme is not set by the user, the companion command {help binsregselect:binsregselect} is used to implement binscatter in a data-driven way.
52
+ Hypothesis testing for parametric specifications of and shape restrictions on the regression function can be conducted via the
53
+ companion command {help binstest:binstest}. Hypothesis testing for pairwise group comparisons can be conducted via the
54
+ companion command {help binspwc: binspwc}. Binscatter estimation based on the least squares method can be conducted via the command {help binsreg: binsreg}.
55
+ {p_end}
56
+
57
+ {p 4 8} A detailed introduction to this command is given in
58
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Stata.pdf":Cattaneo, Crump, Farrell and Feng (2022b)}.
59
+ Companion R and Python packages with the same capabilities are available (see website below).
60
+ {p_end}
61
+
62
+ {p 4 8} Companion commands: {help binstest:binstest} for hypothesis testing of parametric specifications and shape restrictions,
63
+ {help binspwc:binspwc} for hypothesis testing for pairwise group comparisons, and
64
+ {help binsregselect:binsregselect} for data-driven binning selection.{p_end}
65
+
66
+ {p 4 8} Related Stata, R and Python packages are available in the following website:{p_end}
67
+
68
+ {p 8 8} {browse "https://nppackages.github.io/":https://nppackages.github.io/}{p_end}
69
+
70
+
71
+ {marker options}{...}
72
+ {title:Options}
73
+
74
+ {dlgtab:Estimand}
75
+
76
+ {p 4 8} {opt deriv(v)} specifies the derivative order of the regression function for estimation and plotting.
77
+ The default is {cmd:deriv(0)}, which corresponds to the function itself.
78
+ {p_end}
79
+
80
+ {p 4 8} {opt at(position)} specifies the values of {it:othercovs} at which the estimated function is evaluated for plotting.
81
+ The default is {cmd:at(mean)}, which corresponds to the mean of {it:othercovs}. Other options are: {cmd:at(median)} for the median of {it:othercovs},
82
+ {cmd:at(0)} for zeros, and {cmd:at(filename)} for particular values of {it:othercovs} saved in another file.
83
+ {p_end}
84
+
85
+ {p 4 8} Note: When {cmd:at(mean)} or {cmd:at(median)} is specified, all factor variables in {it:othercovs} (if specified) are excluded from the evaluation (set as zero).
86
+ {p_end}
87
+
88
+ {p 4 8}{opt nolink} specifies that the function within the inverse link (logistic) function be reported instead of the conditional probability function.
89
+ {p_end}
90
+
91
+ {dlgtab:Dots}
92
+
93
+ {p 4 8} {opt dots(dotsopt)} sets the degree of polynomial and the number of smoothness for point estimation and plotting as "dots".
94
+ If {cmd:dots(p s)} is specified, a piecewise polynomial of degree {it:p} with {it:s} smoothness constraints is used.
95
+ The default is {cmd:dots(0 0)}, which corresponds to piecewise constant (canonical binscatter).
96
+ If {cmd:dots(T)} is specified, the default {cmd:dots(0 0)} is used unless the degree {it:p} and smoothness {it:s} selection
97
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
98
+ If {cmd:dots(F)} is specified, the dots are not included in the plot.
99
+ {p_end}
100
+
101
+ {p 4 8} {opt dotsgrid(dotsgridoption)} specifies the number and location of dots within each bin to be plotted.
102
+ Two options are available: {it:mean} and a {it:numeric} non-negative integer.
103
+ The option {opt dotsgrid(mean)} adds the sample average of {it:indvar} within each bin to the grid of evaluation points.
104
+ The option {opt dotsgrid(#)} adds {it:#} number of evenly-spaced points to the grid of evaluation points for each bin.
105
+ Both options can be used simultaneously: for example, {opt dotsgrid(mean 5)} generates six evaluation points within each bin
106
+ containing the sample mean of {it:indvar} within each bin and five evenly-spaced points.
107
+ Given this choice, the dots are point estimates evaluated over the selected grid within each bin.
108
+ The default is {opt dotsgrid(mean)}, which corresponds to one dot per bin evaluated at
109
+ the sample average of {it:indvar} within each bin (canonical binscatter).
110
+ {p_end}
111
+
112
+ {p 4 8} {opt dotsplotopt(dotsoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the plotted dots.
113
+ {p_end}
114
+
115
+ {dlgtab:Line}
116
+
117
+ {p 4 8} {opt line(lineopt)} sets the degree of polynomial and the number of smoothness constraints
118
+ for plotting as a "line". If {cmd:line(p s)} is specified, a piecewise polynomial of
119
+ degree {it:p} with {it:s} smoothness constraints is used.
120
+ If {cmd:line(T)} is specified, {cmd:line(0 0)} is used unless the degree {it:p} and smoothness {it:s} selection
121
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
122
+ If {cmd:line(F)} or {cmd:line()} is specified, the line is not included in the plot.
123
+ The default is {cmd:line()}.
124
+ {p_end}
125
+
126
+ {p 4 8} {opt linegrid(#)} specifies the number of evaluation points of an evenly-spaced grid within each bin used for evaluation of the point estimate set by the {cmd:line(p s)} option.
127
+ The default is {cmd:linegrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin for fitting/plotting the line.
128
+ {p_end}
129
+
130
+ {p 4 8} {opt lineplotopt(lineoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the plotted line.
131
+ {p_end}
132
+
133
+ {dlgtab:Confidence Intervals}
134
+
135
+ {p 4 8} {opt ci(ciopt)} specifies the degree of polynomial and the number of smoothness constraints
136
+ for constructing confidence intervals. If {cmd:ci(p s)} is specified, a piecewise polynomial of
137
+ degree {it:p} with {it:s} smoothness constraints is used.
138
+ If {cmd:ci(T)} is specified, {cmd:ci(1 1)} is used unless the degree {it:p} and smoothness {it:s} selection
139
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
140
+ If {cmd:ci(F)} or {cmd:ci()} is specified, the confidence intervals are not included in the plot.
141
+ The default is {cmd:ci()}.
142
+ {p_end}
143
+
144
+ {p 4 8} {opt cigrid(cigridoption)} specifies the number and location of evaluation points in the grid
145
+ used to construct the confidence intervals set by the {opt ci(p s)} option.
146
+ Two options are available: {it:mean} and a {it:numeric} non-negative integer.
147
+ The option {opt cigrid(mean)} adds the sample average of {it:indvar} within each bin to the grid of evaluation points.
148
+ The option {opt cigrid(#)} adds {it:#} number of evenly-spaced points to the grid of evaluation points for each bin.
149
+ Both options can be used simultaneously: for example, {opt cigrid(mean 5)} generates six evaluation points within each bin
150
+ containing the sample mean of {it:indvar} within each bin and five evenly-spaced points.
151
+ The default is {opt cigrid(mean)}, which corresponds to one evaluation point set at
152
+ the sample average of {it:indvar} within each bin for confidence interval construction.
153
+ {p_end}
154
+
155
+ {p 4 8} {opt ciplotopt(rcapoption)} standard graphs options to be passed on to the
156
+ {help twoway:twoway} command to modify the appearance of the confidence intervals.
157
+ {p_end}
158
+
159
+ {dlgtab:Confidence Band}
160
+
161
+ {p 4 8} {opt cb(cbopt)} specifies the degree of polynomial and the number of smoothness constraints
162
+ for constructing the confidence band. If {cmd:cb(p s)} is specified, a piecewise polynomial of
163
+ degree {it:p} with {it:s} smoothness constraints is used.
164
+ If the option {cmd:cb(T)} is specified, {cmd:cb(1 1)} is used unless the degree {it:p} and smoothness {it:s} selection
165
+ is requested via the option {cmd:pselect()} (see more details in the explanation of {cmd:pselect()}).
166
+ If {cmd:cb(F)} or {cmd:cb()} is specified, the confidence band is not included in the plot.
167
+ The default is {cmd:cb()}.
168
+ {p_end}
169
+
170
+ {p 4 8} {opt cbgrid(#)} specifies the number of evaluation points of an evenly-spaced grid within each bin used for evaluation of the point estimate set by the {cmd:cb(p s)} option.
171
+ The default is {cmd:cbgrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin for confidence band construction.
172
+ {p_end}
173
+
174
+ {p 4 8} {opt cbplotopt(rareaoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the confidence band.
175
+ {p_end}
176
+
177
+ {dlgtab:Global Polynomial Regression}
178
+
179
+ {p 4 8} {opt polyreg(p)} sets the degree {it:p} of a global polynomial regression model for plotting.
180
+ By default, this fit is not included in the plot unless explicitly specified.
181
+ Recommended specification is {cmd:polyreg(3)}, which adds a cubic polynomial fit of the regression function of interest to the binned scatter plot.
182
+ {p_end}
183
+
184
+ {p 4 8} {opt polyreggrid(#)} specifies the number of evaluation points of an evenly-spaced grid within each bin
185
+ used for evaluation of the point estimate set by the {cmd:polyreg(p)} option.
186
+ The default is {cmd:polyreggrid(20)}, which corresponds to 20 evenly-spaced evaluation points within each bin for confidence interval construction.
187
+ {p_end}
188
+
189
+ {p 4 8} {opt polyregcigrid(#)} specifies the number of evaluation points of an evenly-spaced grid within each bin used for
190
+ constructing confidence intervals based on polynomial regression set by the {cmd:polyreg(p)} option.
191
+ The default is {cmd:polyregcigrid(0)}, which corresponds to not plotting confidence intervals for the global polynomial regression approximation.
192
+ {p_end}
193
+
194
+ {p 4 8} {opt polyregplotopt(lineoption)} standard graphs options to be passed on to the {help twoway:twoway} command to modify the appearance of the global polynomial regression fit.
195
+ {p_end}
196
+
197
+ {dlgtab:Subgroup Analysis}
198
+
199
+ {p 4 8} {opt by(varname)} specifies the variable containing the group indicator to perform subgroup analysis;
200
+ both numeric and string variables are supported.
201
+ When {opt by(varname)} is specified, {cmdab:binsprobit} implements estimation and inference for each subgroup separately,
202
+ but produces a common binned scatter plot.
203
+ By default, the binning structure is selected for each subgroup separately,
204
+ but see the option {cmd:samebinsby} below for imposing a common binning structure across subgroups.
205
+ {p_end}
206
+
207
+ {p 4 8} {cmd:bycolors(}{it:{help colorstyle}list}{cmd:)} specifies an ordered list of colors for plotting each subgroup series defined by the option {opt by()}.
208
+ {p_end}
209
+
210
+ {p 4 8} {cmd:bysymbols(}{it:{help symbolstyle}list}{cmd:)} specifies an ordered list of symbols for plotting each subgroup series defined by the option {opt by()}.
211
+ {p_end}
212
+
213
+ {p 4 8} {cmd:bylpatterns(}{it:{help linepatternstyle}list}{cmd:)} specifies an ordered list of line patterns for plotting each subgroup series defined by the option {opt by()}.
214
+ {p_end}
215
+
216
+ {dlgtab:Binning/Degree/Smoothness Selection}
217
+
218
+ {p 4 8} {opt nbins(nbinsopt)} sets the number of bins for partitioning/binning of {it:indvar}.
219
+ If {cmd:nbins(T)} or {cmd:nbins()} (default) is specified, the number of bins is selected via the companion command {help binsregselect:binsregselect}
220
+ in a data-driven, optimal way whenever possible. If a {help numlist:numlist} with more than one number is specified,
221
+ the number of bins is selected within this list via the companion command {help binsregselect:binsregselect}.
222
+ {p_end}
223
+
224
+ {p 4 8} {opt binspos(position)} specifies the position of binning knots.
225
+ The default is {cmd:binspos(qs)}, which corresponds to quantile-spaced binning (canonical binscatter).
226
+ Other options are: {cmd:es} for evenly-spaced binning, or a {help numlist} for manual specification of
227
+ the positions of inner knots (which must be within the range of {it:indvar}).
228
+ {p_end}
229
+
230
+ {p 4 8} {opt binsmethod(method)} specifies the method for data-driven selection of the number of bins via
231
+ the companion command {help binsregselect:binsregselect}.
232
+ The default is {cmd:binsmethod(dpi)}, which corresponds to the IMSE-optimal direct plug-in rule.
233
+ The other option is: {cmd:rot} for rule of thumb implementation.
234
+ {p_end}
235
+
236
+ {p 4 8} {opt nbinsrot(#)} specifies an initial number of bins value used to construct the DPI number of bins selector.
237
+ If not specified, the data-driven ROT selector is used instead.
238
+ {p_end}
239
+
240
+ {p 4 8} {opt samebinsby} forces a common partitioning/binning structure across all subgroups specified by the option {cmd:by()}.
241
+ The knots positions are selected according to the option {cmd:binspos()} and using the full sample.
242
+ If {cmd:nbins()} is not specified, then the number of bins is selected via the companion command
243
+ {help binsregselect:binsregselect} and using the full sample.
244
+ {p_end}
245
+
246
+ {p 4 8} {opt randcut(#)} specifies the upper bound on a uniformly distributed variable used to draw a subsample
247
+ for bins/degree/smoothness selection.
248
+ Observations for which {cmd:runiform()<=#} are used. # must be between 0 and 1.
249
+ By default, max(5,000, 0.01n) observations are used if the samples size n>5,000.
250
+ {p_end}
251
+
252
+ {p 4 8} {opt pselect(numlist)} specifies a list of numbers within which the degree of polynomial {it:p} for
253
+ point estimation is selected. Piecewise polynomials of the selected optimal degree {it:p}
254
+ are used to construct dots or line if {cmd:dots(T)} or {cmd:line(T)} is specified,
255
+ whereas piecewise polynomials of degree {it:p+1} are used to construct confidence intervals
256
+ or confidence band if {cmd:ci(T)} or {cmd:cb(T)} is specified.
257
+ {p_end}
258
+
259
+ {p 4 8} {opt sselect(numlist)} specifies a list of numbers within which
260
+ the number of smoothness constraints {it:s}
261
+ for point estimation. Piecewise polynomials with the selected optimal
262
+ {it:s} smoothness constraints are used to construct dots or line
263
+ if {cmd:dots(T)} or {cmd:line(T)} is specified,
264
+ whereas piecewise polynomials with {it:s+1} constraints are used to construct
265
+ confidence intervals or confidence band if {cmd:ci(T)} or {cmd:cb(T)} is specified.
266
+ If not specified, for each value {it:p} supplied in the
267
+ option {cmd:pselect()}, only the piecewise polynomial with the maximum smoothness is considered, i.e., {it:s=p}.
268
+ {p_end}
269
+
270
+ {p 4 8} Note: To implement the degree or smoothness selection, in addition to {cmd:pselect()}
271
+ or {cmd:sselect()}, {cmd:nbins(#)} must be specified.
272
+ {p_end}
273
+
274
+ {dlgtab:Simulation}
275
+
276
+ {p 4 8} {opt nsims(#)} specifies the number of random draws for constructing confidence bands.
277
+ The default is {cmd:nsims(500)}, which corresponds to 500 draws from a standard Gaussian random vector of size [(p+1)*J - (J-1)*s].
278
+ A large number of random draws is recommended to obtain the final results.
279
+ {p_end}
280
+
281
+ {p 4 8} {opt simsgrid(#)} specifies the number of evaluation points of an evenly-spaced grid
282
+ within each bin used for evaluation of the supremum operation needed to construct confidence bands.
283
+ The default is {cmd:simsgrid(20)}, which corresponds to 20 evenly-spaced evaluation points
284
+ within each bin for approximating the supremum operator.
285
+ A large number of evaluation points is recommended to obtain the final results.
286
+ {p_end}
287
+
288
+ {p 4 8} {opt simsseed(#)} sets the seed for simulations.
289
+ {p_end}
290
+
291
+ {dlgtab:Mass Points and Degrees of Freedom}
292
+
293
+ {p 4 8} {opt dfcheck(n1 n2)} sets cutoff values for minimum effective sample size checks,
294
+ which take into account the number of unique values of {it:indvar} (i.e., adjusting for the number of mass points),
295
+ number of clusters, and degrees of freedom of the different statistical models considered.
296
+ The default is {cmd:dfcheck(20 30)}. See Cattaneo, Crump, Farrell and Feng (2022b) for more details.
297
+ {p_end}
298
+
299
+ {p 4 8} {opt masspoints(masspointsoption)} specifies how mass points in {it:indvar} are handled.
300
+ By default, all mass point and degrees of freedom checks are implemented.
301
+ Available options:
302
+ {p_end}
303
+ {p 8 8} {opt masspoints(noadjust)} omits mass point checks and the corresponding effective sample size adjustments.{p_end}
304
+ {p 8 8} {opt masspoints(nolocalcheck)} omits within-bin mass point and degrees of freedom checks.{p_end}
305
+ {p 8 8} {opt masspoints(off)} sets {opt masspoints(noadjust)} and {opt masspoints(nolocalcheck)} simultaneously.{p_end}
306
+ {p 8 8} {opt masspoints(veryfew)} forces the command to proceed as if {it:indvar} has only a few number of mass points (i.e., distinct values).
307
+ In other words, forces the command to proceed as if the mass point and degrees of freedom checks were failed.{p_end}
308
+
309
+ {dlgtab:Standard Error}
310
+
311
+ {p 4 8} {cmd:vce(}{it:{help vcetype}}{cmd:)} specifies the {it:vcetype} for variance estimation used by the command {help probit##options:probit}.
312
+ The default is {cmd:vce(robust)}.
313
+ {p_end}
314
+
315
+ {p 4 8} {opt asyvar(on/off)} specifies the method used to compute standard errors.
316
+ If {cmd:asyvar(on)} is specified, the standard error of the nonparametric component is used
317
+ and the uncertainty related to other control variables {it:othercovs} is omitted.
318
+ Default is {cmd:asyvar(off)}, that is, the uncertainty related to {it:othercovs} is taken into account.
319
+ {p_end}
320
+
321
+ {dlgtab:Other Options}
322
+
323
+ {p 4 8} {opt level(#)} sets the nominal confidence level for confidence interval and confidence band estimation.
324
+ Default is {cmd:level(95)}.
325
+ {p_end}
326
+
327
+ {p 4 8} {opt probitopt(probit_option)} options to be passed on to the command {help probit##options:probit}.
328
+ For example, options that control for the optimization process can be added here.
329
+ {p_end}
330
+
331
+ {p 4 8}{opt usegtools(on/off)} forces the use of several commands in the community-distributed Stata package {cmd:gtools} to speed the computation up, if {it:on} is specified.
332
+ Default is {cmd:usegtools(off)}.
333
+ {p_end}
334
+
335
+ {p 4 8} For more information about the package {cmd:gtools}, please see {browse "https://gtools.readthedocs.io/en/latest/index.html":https://gtools.readthedocs.io/en/latest/index.html}.
336
+ {p_end}
337
+
338
+ {p 4 8} {opt noplot} omits binscatter plotting.
339
+ {p_end}
340
+
341
+ {p 4 8} {opt savedata(filename)} specifies a filename for saving all data underlying the binscatter plot (and more).
342
+ {p_end}
343
+
344
+ {p 4 8} {opt replace} overwrites the existing file when saving the graph data.
345
+ {p_end}
346
+
347
+ {p 4 8} {opt plotxrange(min max)} specifies the range of the x-axis for plotting. Observations outside the range are dropped in the plot.
348
+ {p_end}
349
+
350
+ {p 4 8} {opt plotyrange(min max)} specifies the range of the y-axis for plotting. Observations outside the range are dropped in the plot.
351
+ {p_end}
352
+
353
+ {p 4 8} {it:{help twoway_options}} any unrecognized options are appended to the end of the twoway command generating the binned scatter plot.
354
+ {p_end}
355
+
356
+
357
+ {marker examples}{...}
358
+ {title:Examples}
359
+
360
+ {p 4 8} Setup{p_end}
361
+ {p 8 8} . {stata sysuse auto}{p_end}
362
+
363
+ {p 4 8} Run a binscatter probit regression and report the plot{p_end}
364
+ {p 8 8} . {stata binsprobit foreign weight mpg}{p_end}
365
+
366
+ {p 4 8} Add confidence intervals and confidence band{p_end}
367
+ {p 8 8} . {stata binsprobit foreign weight mpg, ci(1 1) nbins(5)}{p_end}
368
+
369
+
370
+ {marker stored_results}{...}
371
+ {title:Stored results}
372
+
373
+ {synoptset 17 tabbed}{...}
374
+ {p2col 5 17 21 2: Scalars}{p_end}
375
+ {synopt:{cmd:e(N)}}number of observations{p_end}
376
+ {synopt:{cmd:e(level)}}confidence level{p_end}
377
+ {synopt:{cmd:e(dots_p)}}degree of polynomial for dots{p_end}
378
+ {synopt:{cmd:e(dots_s)}}smoothness of polynomial for dots{p_end}
379
+ {synopt:{cmd:e(line_p)}}degree of polynomial for line{p_end}
380
+ {synopt:{cmd:e(line_s)}}smoothness of polynomial for line{p_end}
381
+ {synopt:{cmd:e(ci_p)}}degree of polynomial for confidence interval{p_end}
382
+ {synopt:{cmd:e(ci_s)}}smoothness of polynomial for confidence interval{p_end}
383
+ {synopt:{cmd:e(cb_p)}}degree of polynomial for confidence band{p_end}
384
+ {synopt:{cmd:e(cb_s)}}smoothness of polynomial for confidence band{p_end}
385
+ {p2col 5 17 21 2: Matrices}{p_end}
386
+ {synopt:{cmd:e(N_by)}}number of observations for each group{p_end}
387
+ {synopt:{cmd:e(Ndist_by)}}number of distinct values for each group{p_end}
388
+ {synopt:{cmd:e(Nclust_by)}}number of clusters for each group{p_end}
389
+ {synopt:{cmd:e(nbins_by)}}number of bins for each group{p_end}
390
+ {synopt:{cmd:e(cval_by)}}critical value for each group, used for confidence bands{p_end}
391
+ {synopt:{cmd:e(imse_var_rot)}}variance constant in IMSE, ROT selection{p_end}
392
+ {synopt:{cmd:e(imse_bsq_rot)}}bias constant in IMSE, ROT selection{p_end}
393
+ {synopt:{cmd:e(imse_var_dpi)}}variance constant in IMSE, DPI selection{p_end}
394
+ {synopt:{cmd:e(imse_bsq_dpi)}}bias constant in IMSE, DPI selection{p_end}
395
+
396
+ {marker references}{...}
397
+ {title:References}
398
+
399
+ {p 4 8} Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2022a.
400
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Binscatter.pdf":On Binscatter}.
401
+ {it:arXiv:1902.09608}.
402
+ {p_end}
403
+
404
+ {p 4 8} Cattaneo, M. D., R. K. Crump, M. H. Farrell, and Y. Feng. 2022b.
405
+ {browse "https://nppackages.github.io/references/Cattaneo-Crump-Farrell-Feng_2022_Stata.pdf":Binscatter Regressions}.
406
+ {it:arXiv:1902.09615}.
407
+ {p_end}
408
+
409
+
410
+ {marker authors}{...}
411
+ {title:Authors}
412
+
413
+ {p 4 8} Matias D. Cattaneo, Princeton University, Princeton, NJ.
414
+ {browse "mailto:[email protected]":[email protected]}.
415
+ {p_end}
416
+
417
+ {p 4 8} Richard K. Crump, Federal Reserve Band of New York, New York, NY.
418
+ {browse "mailto:[email protected]":[email protected]}.
419
+ {p_end}
420
+
421
+ {p 4 8} Max H. Farrell, University of Chicago, Chicago, IL.
422
+ {browse "mailto:[email protected]":[email protected]}.
423
+ {p_end}
424
+
425
+ {p 4 8} Yingjie Feng, Tsinghua University, Beijing, China.
426
+ {browse "mailto:[email protected]":[email protected]}.
427
+ {p_end}
428
+