Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Order of execution of nested loops in STATA

    Dear statalists,
    As freshman of STATA, I'm currently facing a problem of understanding the execution of nested loops. Part of my project needs of integrate the effect of cigarettes. Variables including type of cig (1=filter, 2=non-filter, 3=hand-rolled), kind/brand of cig (maximum is 7), amount of smoking cig (pack)and starting and stopping age of each kind of cig (from 1 to 93, and we only documented cig with time length longer than 1 year) .The commands like below:
    Click image for larger version

Name:	_20180528134040.png
Views:	1
Size:	17.9 KB
ID:	1446282

    I feel puzzled about the reason of set CigEt `k' as 0 here, in fact, I am wondering the order or execution of these 3 nested loops.
    Looking forward your reply. Thank you very much!
    Yue

  • #2
    Well, I don't quite know what this code is supposed to do, but I can explain the order of execution.

    It begins by setting k = 1, CigEt1 = 0, y = 1 and z = 1. The code between -forvalues z = 1/7 {- and its closing } is then executed with these values. Next that same code is executed with k = 1, y = 1 and z = 2. Then it is executed with k = 1, y = 1 and z = 3..... and with k = 1, y = 1, and z = 7. Then y is changed to 2, and we iterate over z = 1, z = 2, ... z = 7. Then y is changed to 3.... etc.

    Finally after executing the code with k = 1, y = 93 and z = 7, k gets reset to 2, CigEt2 is set to 0, y goes back to 1 and z goes back to 1, and that block of code is executed again. The whole sequence over all values of y = 1 through 93 with each value of z = 1 through 7 is done. And then after executing the block with k = 2, y = 93, and z = 7, we get the final repeat of the outermost loop. That is, k is set to 3, CigEt3 is set to 0, and y and z go back to 1. Then all combinations of y (1 through 93) and z (1 through 7) are used again. After that all of the loops are done.

    The reason for -gen CigEt`k' = 0- is simply to initialize the value of CigEt`k' before it is used inside the innermost loop. If that initialization were not done, when you hit -replace Cig`k'IntAge`y' = CigEt`k'....- you would get an error message telling you that the variable CigEt`k' does not exist.

    In the future, when showing example code, please do not show a screenshot. What you showed was barely readable on my computer, and, often as not, screenshots are completely unreadable. Instead, please show code by copy/pasting it from your do file into the Forum editor between code delimiters. If you are not familiar with code delimiters, read the Forum FAQ, with attention to #12 for instructions.

    Comment

    Working...
    X