Announcement

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

  • Using foreach numlist for more than one variable

    Hello there,

    Could you please let me know how can i use foreach numlist loop for more than one variable (let us say x1 x2 x3......) based on the following code?


    foreach a of numlist 1 2 3 4 6 7 {

    tab y x1 if x1= ‘a’

    }



  • #2
    Your syntax is illegal twice over, as you need a double equals sign to test for equality and a left-hand quote mark to open a macro reference:

    Code:
    foreach a of numlist 1 2 3 4 6 7 {
       tab y x1 if x1 == `a'
    }
    That said, experienced users would rewrite this as

    Code:
    forval a = 1/7 {
        tab y x1 if x1 == `a'
    }
    while noting that

    Code:
    tab y x1
    or at most

    Code:
    tab y x1 if inrange(x1, 1, 7)
    is likely to be what you want. If you have a specific reason for what you asked for, please tell us what it is.

    From the characters you use, I fear that a word processor was used somewhere. The quote marks used by Stata are never curly.

    PS After 2 years as a member and 20 posts, it's time to read the entire FAQ Advice, please, and to start using CODE delimiters.
    Last edited by Nick Cox; 28 Oct 2018, 06:30.

    Comment


    • #3
      I agree with Nick that
      Code:
      tab y x1 if x1 == `a'
      seems a very unlikely thing to want to do, since the result will be a tab with just one column for the single value of x1.

      Building on Nick's answer, I am going to guess that the loop you wrote was your attempt to produce the following
      Code:
      tab y x1
      tab y x2
      tab y x3
      tab y x4
      tab y x5
      tab y x6
      tab y x7
      which could be accomplished with
      Code:
      forvalues a = 1/7 {
          tab y x`a'
          }
      Or, if x1-x7 are the only variables beginning with x,
      Code:
      foreach xvar of varlist x*  {
          tab y `xvar'
          }

      Comment


      • #4
        William Lisowski's guess is very interesting. Note for his case

        Code:
        tab2 y x1 x2 x3 x4 x5 x6 x7, firstonly 
        gets you there in one.

        Comment

        Working...
        X