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

  • Specificity of "i" in local macros?

    Hi all,

    I have a loop that works, but I would like to understand why it works. Would appreciate your help!

    The data I am working with is made up. It is a combination of birth data (birth ID and the birth month) and monthly precipitation data for January through May (attached as Excel file; could not figure out how to attach as .dta).

    The code creates a new field called "birthprecip" and populates it with the precipitation of the month in which the birth took place. I'm pasting the code below:

    gen birthprecip = .
    local i = 1
    foreach month in jan feb mar april {
    replace birthprecip = precip`month' if birthmo==`i'
    local i = `i'+1

    My specific questions, and what I could figure out for each of them based on playing with the code, are as follows:

    1) Do both of the macros have to use i? Yes, but why?
    I thought local could be used with anything, but "i" appears to have some special meaning, like telling Stata to pay attention to the order.

    2) Why do you need both macros? What is the purpose of each?
    I think the first macro is telling Stata that the value of the first entry in the list is 1. And the second is telling Stata: for each new item in the month list, add 1 to the first i, which was =1. It appears that using "i" also tells Stata not to add 1 to the first observation.

    3) Does the order of the months in the list matter?
    Yes. This is probably related to the special meaning of "i", for which I could not find documentation online or in Stata itself.

    4) Regarding the different things I did with the code (please see attached Do file), why do birthprecip3, 5, 10 and 11 all populate with April data?
    Can't figure this out.

    Attached Files
    Last edited by Felipe Munoz Castillo; 10 Mar 2020, 14:38.