Announcement

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

  • Using multiple varlist

    Hello,

    I want to run a command where I have 2 varlist, and want to calculate the mean of variable in first varlist if the respective variable at same position in varlist 2 has observations equal to 1.

    Code:
    local varlist1 a b c
    local varlist2 d e f
    foreach var of varlist1 & var2 of varlist2 {
        tabstat `var', stats(mean), if `var2'==1
    }
    This code is giving me an error of "invalid syntax".

  • #2
    something like this might work.

    Code:
    clear
    set obs 1000
    
    g a = rnormal(1,1)
    g b = rnormal(2,2)
    g c = rnormal(3,3)
    
    g d = runiform()>0.5
    g e = runiform()>0.5
    g f = runiform()>0.5
    
    
    local varlist1 a b c
    local varlist2 d e f
    
    local c = 1
    foreach var in `varlist1' {
        local met `: word `c' of `varlist2''
        qui summ `var' if `met'==1
        di "Mean `var' at `met'==1 " r(mean)
        local c = `c' + 1
    }

    Comment


    • #3
      If I understand this correctly, this is what you want

      Code:
      tabstat a if d == 1, stats(mean)
      tabstat b if e == 1, stats(mean)
      tabstat c if f == 1, stats(mean)
      which is shorter and simpler than what you have.

      If your question is proxy for one with a longer variable list, then a loop is a serious candidate, but your syntax doesn't match any allowed form. For a start the keyword of may be used only once with foreach and it must always be followed by another keyword out of a small restricted list. In essence, what is not allowed according to the help of foreach really is forbidden. It's not a source of simple style that can be made complicated according to what you would like the syntax to be.

      There are several ways to loop over two lists at once. Here are two:

      Code:
      * #1
      local varlist2 d e f
      
      foreach v in a b c {
            gettoken this varlist2 : varlist2
            tabstat `v' if `this' == 1
      }
      
      * #2
      local varlist1 a b c
      local varlist2 d e f
      
      forval j = 1/3 {
            local x : word `j' of `varlist1'
            local y : word `j' of `varlist2'
            tabstat `x' if `y' == 1. stats(mean)
      }
      Much more discussion at https://journals.sagepub.com/doi/pdf...6867X211063415

      If your question is about nested loops, so that in this example you want all 3 x 3 combinations, then that is different.

      Code:
      foreach v in a b c {        
          foreach w in d e f {              
              tabstat `v' if `w' == 1, stats(mean)      
          }
      }

      Comment


      • #4
        Nick's #1 is tight. I learned something today.

        Comment

        Working...
        X