Announcement

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

  • Multiple loops in forvalues / foreach

    Hello!
    I have a set of 4 variables and a set of 4 conditions. I would like to run non-parametric tests (ranksum) over pairs of the two conditions for each variable. After some huffig and puffing I managed to create a loop to run pairwise tests for each variable individually:

    local treatment "T1 T2 T3 T4"
    local var "V1 V2 V3 V4"

    forvalues i=1/4 {
    forvalues j=`=`i'+1'/4 {
    local this_treatment `: word `i' of `treatment''
    local other_treatment `: word `j' of `treatment''
    di "`this_treatment'" " `other_treatment'"
    ranksum V1 if `this_treatment'==1 | `other_treatment'==1 ,by(`this_treatment')
    }
    }

    Now, if I try to plug in the loop over the 4 vars, as in the following code, I get the answer that there are too many variables for the test. Any solution? Thanks in advance!

    forvalues i=1/4 {
    forvalues j=`=`i'+1'/4 {
    foreach x in `var' {
    local this_treatment `: word `i' of `treatment''
    local other_treatment `: word `j' of `treatment''
    di "`x'" " `this_treatment' " " `other_treatment' "
    ranksum `x' if `this_treatment'==1 | `other_treatment'==1 ,by(`this_treatment')
    }
    }
    }
    Last edited by Gianluca Grimalda; 03 Apr 2019, 09:39.

  • #2
    I can't reproduce your problem. Your code, copied and pasted into my Stata do-editor, with a toy data set containing variables T1-T4 and V1-V4 works without error.

    Comment


    • #3
      Like Clyde, I can't see a problem.

      This is a tweak to your first set of loops.

      Code:
      forvalues i=1/4 {
          forvalues j=`=`i'+1'/4 {
              di "T`i' T`j'"
              ranksum V1 if T`i'==1 | T`j'==1 , by(T`i')
          }
      }

      Comment


      • #4
        Thanks so much for your attention! Glad to see the code worked well, probably repeated attempts to run the loops made the code lose sight of their original definition. Thank you Nick for the suggestion. I was wondering how to "index" variables and I can now see it is easier than I had thought! Thanks so much again!

        Comment


        • #5
          Hi, Mr. Cox,

          What should do if I want the second loop includes periods from i+1 to i+3/

          Best,
          Zichun

          Comment


          • #6
            That depends on how far the loop should go, does it not? I think more detail would help here.

            Comment

            Working...
            X