-
Notifications
You must be signed in to change notification settings - Fork 4
/
05-programming.dyndoc
997 lines (781 loc) · 27.3 KB
/
05-programming.dyndoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
# Programming & Advanced Features
Stata features the ability to create user-written commands. These can range from
simple data manipulation commands to completely new statistical models. This is
an advanced feature that not many users will need.
However, there are several components of the programming capabilities which are
very useful even without writing your own commands. Here we'll discuss several.
Let's open a fresh version of "auto":
```stata
<<dd_do>>
sysuse auto, clear
<</dd_do>>
```
## Macros
While variables stored as strings aren't of much use to us, strings stored as
other strings can be quite useful. Imagine the following scenario: You have a
collection of 5 variables that you want to perform several different operations
on. You might have code like this:
```stata
list var1 var2 var3 var4 var5 in 1/5
summarize var1 var2 var3 var4 var5
label define mylab 0 "No" 1 "Yes"
label values var1 var2 var3 var4 var5 mylab
duplicates list var1 var2 var3 var4 var5
```
This can get extremely tedious as the number of variables and commands
increases. You could copy and paste a lot, but even that takes a lot of effort.
Instead, we can store the list of variables (strictly speaking, the string which
contains the list of variables) in a shorter key string, and refer to that
instead!
```stata
local vars = "var1 var2 var3 var4 var5"
list `vars' in 1/5
summarize `vars'
label define mylab 0 "No" 1 "Yes"
label values `vars' mylab
duplicates list `vars'
```
The first command, `local`, defines what is known as a "local macro". Whenever
it is referred to, wrapped in a backtick (to the left of the 1 key at the
top-left of the keyboard) and a single quote, Stata replaces it with the
original text. So when you enter
```stata
list `vars' in 1/5
```
Stata immediately replaces `` `vars'`` with `var1 var2 var3 var4 var5`, then
executes
```stata
list var1 var2 var3 var4 var5 in 1/5
```
**Important**: Local macros are deleted as soon as code finishes executing! That
means that you must use them in a do-file, and **you must run all lines which
create and access the macro at the same time**, by highlighting them all.
If your macro contains text that should be quoted, you still need to quote it
when accessing. For example, if you had
```stata
label variable price1 "Price (in dollars) at Time Point 1"
label variable price2 "Price (in dollars) at Time Point 2"
```
you could instead write
```stata
local pricelab = "Price (in dollars) at Time Point"
label variable price1 "`pricelab' 1"
label variable price2 "`pricelab' 2"
```
You can use `display` to print the content of macros to the output to preview them.
```stata
<<dd_do>>
local test = "abc"
display "`test'"
<</dd_do>>
```
You may occasionally see code that excludes the `=` in defining a macro (e.g.
`local vars "var1 var2"`). This matters when working with numeric macros. Using
an `=` forces the evaluates the macro, exlcuding it doesn't. For example,
```stata
<<dd_do>>
local x 1 + 3
display "`x'"
local y = 1 + 3
display "`y'"
<</dd_do>>
```
Note the use of quotations there. `display` would evaluate numerics regardless
of `=` or not, so by treating it as a string, we can see the difference.
### Global macros
`local` defines a "local macro"; `global` defines a "global macro". Global
macros persist between runs - whereas a local macro is removed after the code
finishing executing, the global stays around.
Global macros are accessesd with `$`:
```stata
<<dd_do>>
global dog "Black Lab"
display "$dog"
<</dd_do>>
```
### Class and Return
Every command in Stata is of a particular type. One major aspect of the type is
what the command "returns". Some commands are n-class, which means they don't
return anything. Some are c-class, which are only used by programmers and rarely
useful elsewhere. The two common ones are e-class and r-class. The distinction
between the two is inconsequential, besides that they store their "returns" in
different places.
Here, `summarize` is a r-class command, so it stores its returns in "return". We
can see them all by `return list`. On the other hand, `mean` (which we haven't
discussed, but basically displays summary statistics similar to `summarize` but
provides some additional functionality) is an e-class command, storing its
results in `ereturn`:
```stata
<<dd_do>>
summarize price
return list
mean price
ereturn list
<</dd_do>>
```
Rather than try and keep track of what gets stored where, if you look at the
very bottom of any help file, it will say something like "`summarize` stores the
following in `r()`:" or "`mean` stores the following in `e()`:", corresponding
to `return` and `ereturn` respectively.
Along with the [One Data](01-the-basics-of-stata.qmd#one-data) principal, Stata
also follows the One _-class principal - meaning you can only view the `return`
or `ereturn` for the most recent command of that class. So if you run a
`summarize` command, then do a bunch of n-class calls (`gsort` for example), the
`return list` call will still give you the returns for that first `summarize`.
However, as soon as you run another r-class command, you lose access to the
first one. You can save any piece of it using a
[macro](05-programming.qmd#macros). For example, to calculate the average
difference in price between foreign and domestic cars^[There are obviously other
ways to compute this, but this gives a flavor of the use.]:
```stata
<<dd_do>>
summarize price if foreign == 1
local fprice = r(mean)
summarize price if foreign == 0
local dprice = r(mean)
display `dprice' - `fprice'
<</dd_do>>
```
## Variable Lists
Introduced in Stata 16, variable lists solves a common technique used in
previous versions of Stata to define a `global` containing a list of variables
to be used later in the document. For example, you might see something like this
at the top of a Do file:
```stata
global predictors x1 x2 x3 x4
```
then further down the document something like
```stata
regress y $predictors
logit z $predictors
```
Stata has formalized this concept with the addition of the `vl` command
(**v**ariable **l**ist). It works similarly to the use of globals: lists of
variables are defined, then later reference via the `$name` syntax. However,
using `vl` has the benefits of improved organization, customizations unique to
variable lists, error checking, and overall convenience.
### Initialization of Variable Lists
To begin using variable lists, `vl set` must be run.
```stata
<<dd_do>>
sysuse auto
vl set
<</dd_do>>
```
This produces a surprisingly large amount of output. When you initialize the use
of variable lists, Stata will automatically create four variable lists, called
the "System variable lists". Every *numeric* variable in the current data set is
automatically placed into one of these four lists:
- `vlcategorical`: Variables which Stata thinks are categorical. These generally
have to be non-negative, integer valued variables with less than 10 unique
values.
- `vlcontinuous`: Variables which Stata thinks are continuous. These generally
are variables which have negative values, have non-integer values, or are
non-negative integers with more than 100 unique values.
- `vluncertain`: Variables which Stata is unsure whether they are continuous or
categorical. These generally are non-negative integer valued variables with
between 10 and 100 unique values.
- `vlother`: Any numeric variables that aren't really useful - either all
missing or constant variables.
There is a potential fifth system variable list, `vldummy`, which is created
when option `dummy` is passed. Unsurprisingly, this will take variables
containing only values 0 and 1 out of `vlcategorical` and into this list.
The "Notes" given below the output are generic; they appear regardless of how
well Stata was able to categorize the variables. They can be suppressed with the
`nonotes` option to `vl set`.
The two thresholds given above, 10 and 100, can be adjusted by the `categorical`
and `uncertain` options. For example,
```stata
vl set, categorical(20) uncertain(50)
```
Running `vl set` on an already `vl`-set data set will result in an error, unless
the `clear` option is given, which will re-generate the lists.
```stata
<<dd_do>>
vl set, dummy nonotes
vl set, dummy nonotes clear
<</dd_do>>
```
In the above, we changed our minds and wanted to include the `vldummy` list, but
since we'd already `vl`-set, we had the `clear` the existing set.
### Viewing lists
When initializing the variable lists, we're treated to a nice table of all
defined lists. We can replay it via
```stata
<<dd_do>>
vl dir
<</dd_do>>
```
To see the actual contents of the variable lists, we'll need to sue `vl list`.
```stata
<<dd_do>>
vl list
<</dd_do>>
```
This output produces one row for each variable *in each variable list it is in*.
We haven't used this yet, but variables can be in multiple lists.
We can list only specific lists:
```stata
<<dd_do>>
vl list vlcategorical
<</dd_do>>
```
or specific variables
```stata
<<dd_do>>
vl list (turn weight)
<</dd_do>>
```
If `turn` was in multiple variable lists, each would appear as a row in this
output.
There's a bit of odd notation which can be used to sort the output by variable
name, which makes it easier to identify variables which appear in multiple
lists.
```stata
<<dd_do>>
vl list (_all), sort
<</dd_do>>
```
The `(_all)` tells Stata to report on all variables, and sorting (when you
specify at least one variable) orders by variable name rather than variable list
name.
This will also list any numeric variables which are not found in **any** list.
#### Moving variables in system lists
After initializing the variable lists, if you plan on using the system lists,
you may need to move variables around (e.g. classifying the `vluncertain`
variables into their proper lists). This can be done via `vl move` which has the
syntax
```stata
vl move (<variables to move>) <destination list>
```
For example, all the variables in `vluncertain` are actually continuous:
```stata
<<dd_do>>
vl list vluncertain
vl move (price mpg trunk weight length turn displacement) vlcontinuous
vl dir
<</dd_do>>
```
Alternatively, since we're moving all variables in `vluncertain`, we can see our
first use of the variable list!
```stata
<<dd_do>>
vl set, dummy nonotes clear
vl move ($vluncertain) vlcontinuous
<</dd_do>>
```
Note that variable lists are essentially just global macros so can be referred
to via `$name`. Note, however, that the `$` is only used when we want to
actually use the variable list as a macro - in this case, we wanted to expand
`vluncertain` into it's list of variables. When we're referring to a variable
list in the `vl` commands, we *do not* use the `$`.
### User Variable Lists
In addition to the System variable lists, you can define your own User variables
lists, which I imagine will be used far more often. These are easy to create
with `vl create`:
```stata
<<dd_do>>
vl create mylist1 = (weight mpg)
vl create mylist2 = (weight length trunk)
vl dir, user
vl list, user
<</dd_do>>
```
Note the addition of the `user` option to `vl list` and `vl dir` to show only
User variable lists and suppress the System variable lists. We can also
demonstrate the odd sorting syntax here:
```stata
<<dd_do>>
vl list (_all), sort user
<</dd_do>>
```
You can refer to variable lists in all the usual shortcut ways:
```stata
vl create mylist = (q x1-x100 z*)
```
We can add labels to variable lists:
```stata
<<dd_do>>
vl label mylist1 "Related to gas consumption"
vl label mylist2 "Related to size"
vl dir, user
<</dd_do>>
```
#### Modifying User Variable Lists
First, note that with User Variable Lists, the `vl move` command **does not
work**. It only works with system variable lists.
We can create new user variable lists which build off old lists with `vl
create`. To add a new variable:
```stata
<<dd_do>>
vl create mylist3 = mylist2 + (gear_ratio)
vl list, user
vl create mylist4 = mylist2 - (turn)
vl list, user
<</dd_do>>
```
Instead of adding (or removing) single variables at a time, we can instead add
or remove lists. Keeping with the comment above, you do *not* use `$` here to
refer to the list.
```stata
<<dd_do>>
vl create mylist5 = mylist2 - mylist1
vl list mylist5
<</dd_do>>
```
However, if we want to simply modify an existing list, a better approach would
be the `vl modify` command. `vl create` and `vl modify` are similar to
`generate` and `replace`; the former creates a new variable list while the later
changes an existing variable list, but the syntax right of the `=` is the same.
```stata
<<dd_do>>
vl modify mylist3 = mylist3 + (headroom)
vl modify mylist3 = mylist3 - (weight)
<</dd_do>>
```
### Dropping variable list
Variable lists can be dropped via `vl drop`
```stata
<<dd_do>>
vl dir, user
vl drop mylist4 mylist5
vl dir, user
<</dd_do>>
```
System lists cannot be dropped; if you run `vl drop vlcontinuous` it just
removes all the variables from it.
### Using Variable Lists
To be explicit, we can use variable lists in any command which would take the
variables in that list. For example,
```stata
<<dd_do>>
describe $mylist3
describe $vlcategorical
<</dd_do>>
```
We can also use them in a modeling setting.
```stata
<<dd_do>>
regress mpg $mylist3
<</dd_do>>
```
However, we'll run into an issue here - how to specify categorical variables or
interactions? The `vl substitute` command creates "factor-variable lists" that
can include factor variable indicators (`i.`), continuous variable indicators
(`c.`), and interactions (`#` or `##`). (The name "factor-variable list" is
slightly disingenuous; you could create a "factor-variable list" that includes
no actual factors, for example, if you wanted to interact two continuous
variables.)
Creating a factor-varible list via `vl substitute` can be done by specifying
variables or variable lists.
```stata
<<dd_do>>
vl substitute sublist1 = mpg mylist3
display "$sublist1"
vl dir
<</dd_do>>
```
Note the use of `display "$listname"` instead of `vl list`. Factor-variable
lists are not just lists of vairables, they also can include the features above,
so must be displayed. Note that in the `vl dir`, "sublist1" has no number of
variables listed, making it stand apart.
We can make this more interesting by actually including continuous/factor
indicatores and/or interactions.
```stata
<<dd_do>>
vl substitute sublist2 = c.mylist1##i.vldummy
display "$sublist2"
<</dd_do>>
```
Note the need to specify that mylist1 is continuous (with `c.`). It follows the
normal convention that Stata assumes predictors in a model are continuous by
default, unless they're invloved in an interaction, in which case it assumes
they are factors by default.
```stata
<<dd_do>>
regress price $sublist2
<</dd_do>>
```
#### Updating factor-variable Lists
Factor-variable lists cannot be directly modified.
```stata
<<dd_do>>
display "$sublist1"
vl modify sublist1 = sublist1 - mpg
<</dd_do>>
```
However, if you create a factor-variable list using only other variable lists,
if those lists get updated, so does the factor-variable list!
```stata
<<dd_do>>
vl create continuous = (turn trunk)
vl create categorical = (rep78 foreign)
vl substitute predictors = c.continuous##i.categorical
display "$predictors"
vl modify continuous = continuous - (trunk)
quiet vl rebuild
display "$predictors"
<</dd_do>>
```
Note the call to `vl rebuild`. Among other things, it will re-generate the
factor-variable lists. (It produces a `vl dir` output without an option to
suppress it, hence the use of
[`quiet`](05-programming.qmd#quieting-the-output).)
### Stored Statistics
You may have noticed that certain characteristics of the variable are reported.
```stata
<<dd_do>>
vl list mylist3
<</dd_do>>
```
This reports some characteristics of the variables (integer, whether it's
non-negative) and the number of unique values. We can also see some other
statistics:
```stata
<<dd_do>>
vl list mylist3, min max obs
<</dd_do>>
```
This is similar to [`codebook`](03-data-management.qmd#summarizing-the-data)
except faster; these characteristics are saved at the time the variable list is
created or modified and not updated automatically. If the data changes, this
does *not* get updated.
```stata
<<dd_do>>
drop if weight < 3000
summarize weight
vl list (weight), min max obs
<</dd_do>>
```
To re-generate these stored statistics, we call `vl set` again, with the
`update` option.
```stata
<<dd_do>>
vl set, update
vl list (weight), min max obs
<</dd_do>>
```
When the `update` option is passed, variable lists are not affected, only stored
statistics are updated.
## Linking data sets
In addition to allowing multiple data sets to be open at a time, we can **link**
frames together such that rows of data in each frames are connected to
each-other and can inter-operate. This requires a linking variable in each data
set which will connect the rows. The two data sets can be at the same levels or
at different levels.
For example, we might have data sets collected from multiple waves of surveys
and follow-ups during which the same people (modulo some non-responses) are
contained in each data set. Then the person ID variable in the data sets would
be the linking variable.
Another example might be one file at the person level, and another file at the
city level. The linking variable would be city name, which would be unique in
the city file, but could potentially be repeated in the person level file.
The command to link files is `frlink` and requires specifying both the linking
variable(s) and the frame to link to.
```stata
frlink 1:1 linkvar, frame(otherframe)
```
Let's load some data from NHANES. Each file contains a row per subject.
```stata
<<dd_do>>
frame reset
frame rename default demographics
frame create diet
frame create bp
import sasxport5 "https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/DEMO_I.XPT", clear
frame diet: import sasxport5 "https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/DR1TOT_I.XPT", clear
frame bp: import sasxport5 "https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/BPX_I.XPT", clear
frame dir
<</dd_do>>
```
So as you can see, the current frame is the "demographics" frame, and the other
frames contains diet and blood pressure information. The variable `seqn` records
person ID.
```stata
<<dd_do>>
frlink 1:1 seqn, frame(bp)
frlink 1:1 seqn, frame(diet)
<</dd_do>>
```
The `1:1` subcommand specifies that it is a 1-to-1 link - each person has no
more than 1 row of data in each file. An alternative is `m:1` which allows
multiple rows in the main file to be linked to a single row in the second frame.
`1:m` is *not allowed* at this point in time.
These commands created two new variables `bp` and `diet` (the same new as the
linked frames) which indicate which row of the linked from is connected with the
given row.
```stata
<<dd_do>>
list bp diet in 25/29
<</dd_do>>
```
Here we see that row 27 in the demographics file was not found in either "bp" or
"diet" and thus has no entry in the `bp` or `diet` variables.
Links are tracked by the variables, we can see the current status of a link via
`frlink describe`:
```stata
<<dd_do>>
frlink describe diet
<</dd_do>>
```
We can see all links from the current frame via `frlink dir`:
```stata
<<dd_do>>
frlink dir
<</dd_do>>
```
To unlink frames, simply drop the variable.
```stata
<<dd_do>>
drop diet
<</dd_do>>
```
Finally, the names of the created variables can be modified via the `generate`
option to `frlink`:
```stata
<<dd_do>>
frlink 1:1 seqn, frame(diet) generate(linkdiet)
frlink dir
<</dd_do>>
```
### Working with linked frames
Once we have linked frames, we can use variables in the linked frame in analyses
on the main frame.
The `frget` command can copy variables from the linked frame into the primary
frame.
```stata
<<dd_do>>
summarize bpxchr
frget bpxchr, from(bp)
summarize bpxchr
<</dd_do>>
```
This merges appropriately, with a `1:1` or `m:1` link, to properly associate the
values of the variable with the right observations.
Alternatively, when using `generate`, we can reference a variable in another
frame.
```stata
<<dd_do>>
generate nonsense = frval(linkdiet, dr1tcalc)/frval(bp, bpxpls) + dmdhrage
<</dd_do>>
```
Note that this calculation used variables from all three frames. A less
nonsensical example might be where we want the percent of a countries population
located in a given state. Imagine we have the primary frame of county data, and
then a separate frame "state" containing state level information.
```stata
generate percentpopulation = population/frval(state, population)
```
## Loops
Using macros can simplify code if you have to use the same string repeatedly,
but what if you want to perform the same command repeatedly with different
variables? Here we can use a `foreach` loop. This is easiest to see with
examples.
```stata
<<dd_do>>
sysuse pop2000, clear
<</dd_do>>
```
The "pop2000" data contains data from the 2000 census, broken down by age and
gender. The values are in total counts, lets say instead we want percentages by
gender. For example, what percentage of Asians in age 25-29 are male? We could
generate this manually.
```stata
<<dd_do>>
generate maletotalperc = maletotal/total
generate femtotalperc = femtotal/total
generate malewhiteperc = malewhite/white
<</dd_do>>
```
This gets tedious fast as we need a total of 12 lines! Notice, however, that
each line has a predictable pattern:
```stata
generate <gender><race>perc = <gender><race>/<race>
```
We can exploit this by creating a `foreach` loop over the racial categories and
only needing a single command.
```stata
<<dd_do>>
drop *perc
foreach race of varlist total-island {
generate male`race'perc = male`race'/`race'
generate fem`race'perc = fem`race'/`race'
}
list *perc in 1, abbreviate(100)
<</dd_do>>
```
Let's breakdown each piece of the command. The command syntax for `foreach` is
```stata
foreach <new macroname> of varlist <list of variables>
```
The loop will create a [macro](05-programming.qmd#macros) that you name (in the
example above, it was named "race"), and repeatedly set it to each subsequent
entry in the list of variables. So in the code above, first "race" is set to
"total", then the two `generate` commands are run. Next, "race" is set to
"white", then the two commands are run. Etc.
Within each of the `generate` commands, we use the backtick-quote notation just
like with [macros](05-programming.qmd#macros).
Finally, we end the `foreach` line with an open curly brace, `{`, and the line
after the last command within the loop has the matching close curly brace, `}`.
We can also nest these loops. Notice that both `generate` statements above are
identical except for "male" vs "fem". Let's put an internal loop:
```stata
<<dd_do>>
drop *perc
foreach race of varlist total-island {
foreach gender in male fem {
generate `gender'`race'perc = `gender'`race'/`race'
}
}
list *perc in 1, ab(100)
<</dd_do>>
```
Each time "race" gets set to a new variable, we enter another loop where
"gender" gets set first to "male" then to "fem". To help visualize it, here is
what "race" and "gender" are set to each time the `gen` command is run:
| `generate` command | "race" | "gender" |
|:------------------:|:----------:|:----------:|
| 1 | total | male |
| 2 | total | fem |
| 3 | white | male |
| 4 | white | fem |
| 5 | black | male |
| 6 | black | fem |
| 7 | indian | male |
| 8 | indian | fem |
| 9 | asian | male |
| 10 | asian | fem |
| 11 | island | male |
| 12 | island | fem |
Notice the syntax of the above two `foreach` differs slightly:
```stata
foreach <macro name> of varlist <variables>
foreach <macro name> in <list of strings>
```
It's a bit annoying, but Stata handles the "of" and "in" slight differently. The
"in" treats any strings on the right as strict. Meaning if the above loop over
race were
```stata
foreach race in total-island
```
then Stata would set "race" to "total-island" and the `generate` command would
run once! By using "of varlist", you are telling Stata that before it sets
"race" to anything, expand the varlist using the [rules such as `*` and
`-`](03-data-management.qmd#referring-to-variables).
There is also
```stata
foreach <macro name> of numlist <list of numbers>
```
The benefit of `of numlist` is that numlists support things like 1/4
representing 1, 2, 3, 4. So
```stata
foreach num of numlist 1 3/5
```
Loops over 1, 3, 4, 5, whereas
```stata
foreach num in 1 3/5
```
loops over just "1" and "3/5".
The use of `in` is for when you need to loop over strings that are neither
numbers nor variables (such as "male" and "fem" from above).
## Suppressing output and errors
There are two useful command prefixes that can be handy while writing more
elaborate Do-files.
### Capturing an error
Imagine the following scenario. You want to write a Do-file that generates a new
variable. However, you may need to re-run chunks of the Do-file repeatedly, so
that the `generate` statement is hit repeatedly. After the first `generate`, we
can't call it again and [need to use `replace`
instead](04-data-manipulation.qmd#replacing-existing-variables). However, if we
used `replace`, it wouldn't work the first time! One solution is to `drop` the
variable before we `generate` it:
```stata
<<dd_do>>
sysuse auto, clear
drop newvar
generate newvar = 1
<</dd_do>>
```
That error, while not breaking the code, is awfully annoying! However, if we
prefix it by `capture`, the error (and *all output from the command*) are
"captured" and hidden.
```stata
<<dd_do>>
list price in 1/5
capture list price in 1/5
list abcd
capture list abcd
<</dd_do>>
```
Therefore, the best way to generate our new variable is
```stata
<<dd_do>>
capture drop newvar
generate newvar = 1
<</dd_do>>
```
#### Return Code
When you `capture` a command that errors, Stata saves the error code in the
`_rc` macro.
```stata
<<dd_do>>
list abc
capture list abc
display _rc
<</dd_do>>
```
If the command does **not** error, `_rc` contains 0.
```stata
<<dd_do>>
capture list price
display _rc
<</dd_do>>
```
This can be used to offer additional code if an error occurs
```stata
capture <some command>
if _rc > 0 {
...
} else {
...
}
```
If the command inside the `capture` runs without error, the `if` block will run.
If the command inside the `capture` errors, the `else` block will run.
Say you wanted to rename a variable if it exists, and if doesn't exist, create
it. (For example, you have to process a large number of files, and in some
files, this variable may be missing for all rows and thus not reported.) You
could run the following:
```stata
capture rename oldvar newvar
if _rc > 0 {
generate newvar = .
}
```
### Quieting the output
`quietly` does the same basic thing as `capture`, except it does not hide
errors. It can be useful combined with [the
returns](05-programming.qmd#class-and-return):
```stata
<<dd_do>>
quietly summarize price
display r(mean)
<</dd_do>>
```
This will come in very handy when you start running statistical models, where
the output can be over a single screen, whereas you only want a small piece of
it.
Just to make the difference between `capture` and `quietly` clear:
```stata
<<dd_do>>
list price in 1/5
quietly list price in 1/5
capture list price in 1/5
list abcd in 1/5
quietly list abcd in 1/5
capture list abcd in 1/5
<</dd_do>>
```
With a command that doesn't error (listing `price`), both `quietly` and
`capture` perform the same. However, with a command that does error, `quietly`
still errors, whereas `capture` just ignores it!