Announcement

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

  • If statement with var names

    Hi,

    I have several loops that run through a series of regressions for a set of dependent variables in the local macro. See below:

    Code:
    local vars var1 var2 ....
    
    foreach depvar in `vars' {
    reg `depvar' controlvars1.....
    ...
    }
    
    foreach depvar in `vars' {
    reg `depvar' controlvars2 .....
    ...
    }
    I am trying to exclude a specific dep var from only 1 of the loops without setting a new local macro. My current code looks like this:

    Code:
    local vars var1 var2 ....
    
    foreach depvar in `vars' {
    if `depvar' != var1 {
    reg `depvar' controlvars1.....
    ...
    }
    However, this does not work. Is there a way to deal with this within the if statement I have? Another iteration that also don't work:
    Code:
    if "`depvar'" != "var1"
    Another note - I would like this to be able to include multiple variables in the excluded list.

    I know I could reset the local without the excluded var but this is not my preference for this workflow.

    I'd appreciate any help statalist can provide.
    Henry
    Last edited by Henry Cust; 28 Mar 2023, 00:20.

  • #2
    n/a
    Last edited by Henry Cust; 28 Mar 2023, 00:17.

    Comment


    • #3
      n/a
      Last edited by Henry Cust; 28 Mar 2023, 00:17.

      Comment


      • #4
        Code:
        if "`depvar'" != "var1"
        is precisely what I would recommend given your taste, so in what sense does it not work?

        From what I understand of your context you want to define the local macro because you are going to use it repeatedly; otherwise i see no virtue in defining a local macro only to use it once and immediately. That is, there is no virtue in this

        Code:
        local vars1 var1 var2
        local controlvars1 cvar1 cvar2
        
        foreach depvar of local vars1  {
        reg `depvar' `controlvars1'
        ...
        }
        
        local vars2 var2 var3
        local controlvars2 cvar2 cvar3
        
        foreach depvar of local vars2 {
        reg `depvar' `controlvars2'
        ...
        }
        rather than this:


        Code:
        foreach depvar in var1 var2 {
        reg `depvar' cvar1 cvar2
        ...
        }
        
        loreach depvar in var2 var3  {
        reg `depvar' cvar2 cvar3
        ...
        }
        Last edited by Nick Cox; 28 Mar 2023, 01:59.

        Comment


        • #5
          I noticed a few strange errors since writing this, including the code excluding other variables from the loops. It turns out a restart was required. Thanks for looking into it Nick.

          For clarity to other readers, as Nick suggests, the following does work.
          Code:
          if "`depvar'" != "var1" {

          Comment

          Working...
          X