Announcement

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

  • How to make inner and outer loop run parallel?

    Hi Everyone,
    I am trying to import chunks of a very large file, clean, then collapse it. My problem is that my outer loop seems to be stuck on the first value, and just overwrites what was created in the previous loop. In hindisght, I should have these run such that i1 corresponds to s1. How can I fix?

    Here is the start of my loop:

    ```
    local LIST 10 20 30 40 50
    forval i =1/5 {

    foreach s of local LIST {
    clear
    di "Outer loop = " `i'
    di "Inner loop = " `s'
    local j = `s'+10
    import delimited "F:\\SaleItems_1\SaleItems_1.csv", varnames(1) encoding(UTF-16) rowrange(`s'000001:`j'000000)

    cd "F:\\WA_pt2"

    save SaleItems_1_pt`i'.dta, replace
    ```
    My issue is clearly that these aren't running parallel. How should I fix this so that i and s move 1 by 1?

    Best, Josh

  • #2
    One approach to demonstrate the technique to get you started in a useful direction is shown.

    Code:
    local mylist 10 20 30 40 50
    forval i =1/5 {
      local s : word `i' of `mylist'
      di "i=`i' s=`s'"
    }
    Result

    Code:
    i=1 s=10
    i=2 s=20
    i=3 s=30
    i=4 s=40
    i=5 s=50

    Comment


    • #3
      Thank you so much!!!

      So if i starts at 3, should I make
      s=`s'-2" ?

      Comment


      • #4
        The idea of local macro i in post #2 is that is a counter, and its intuitive to count elements from to 1, 2, ..., N. As the loop iterates it counts out the element from mylist, but you can extend this concept to also count from other lists for use inside the loop.

        If you can express a mathematical relationship between s and i, then you could define this in your loop. But, your example in #3 doesn't show this. You might instead want this inside your loop:

        Code:
        local s = `i' + 2
        Then the loop just counts 1 to 5 (say) and a will always be 2 more than i (3 to 7). The example just used your listed values of 10, 20, etc and I did not assume that there would necessarily be mathematical relationship, but that this was just an arbitrary list.

        Comment


        • #5
          The key point is that loops in parallel are never nested loops. They are just single loops with machinery to work on two or more lists at once. I feel happy at leaving that remark epigrammatic as there is much more on the theme at

          https://journals.sagepub.com/doi/pdf...6867X211063415

          Comment

          Working...
          X