Announcement

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

  • Subsetting inputs in foreach

    I am trying to execute the same commands for two different files using foreach. The problem is that I only want to run melogit for one file. I receive an error when I include an if-statement in melogit. Below is an example:

    Code:
    foreach file in file1 file2 {
    
    use  `file', clear 
    
    *********************************************
    **some code, including other models
    *********************************************
    
    *I only want to run this model on file1
    melogit dv v1 v2* if `file' = file1 || re1: || re2:
    }
    Is this possible?


  • #2

    Code:
    *I only want to run this model on file1  
    
    if "`file'" == "file1" {      
          melogit dv v1 v2* || re1: || re2:
    }

    Comment


    • #3
      You do not explain what file1 and file2 are. I will assume that they are names of files in reality, and not the text strings "file1" and "file2"

      Code:
      foreach file in file1 file2 {
          use `file', clear
          // SOME CODE, INCLUDING OTHER MODELS
      
          if "`file'" == "file1" { // NOTE ==, NOT =; ALSO NOTE USE OF QUOTATION MARKS
              melogit dv v1 v2* || re1: || re2:
          }
      // ETC.
      The distinction between an -if- condition (which you have incorrectly used here) and an -if- command is the key here. -if- conditions follow (or, occasionally, as with -melogit- appear embedded in, the single command they effect and restrict the execution of that command to some subset of the data in memory. That is not what you want to do here. What you want to do is restrict whether -melogit- is executed at all: if you are on the iteration for file1 you want to run the -melogit-, with all of the data, but if you are on file2, you do not want to run it at all. This requires the -if- command. These precede the command(s) they guard, and a single -if- command can apply to a block of several consecutive commands enclosed in curly braces ({ }).

      I have also corrected a few miscellaneous syntax errors here.

      Added: Crossed with #2.
      Last edited by Clyde Schechter; 13 Dec 2022, 12:49.

      Comment


      • #4
        That works great. Thank you Nick and Clyde for your helpful feedback.

        Comment

        Working...
        X