Announcement

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

  • Strpos and Local

    I would like to define a local based on a string in another local:

    Code:
    foreach outcome in out_num out_can {
          if strpos("`outcome","num")>0 local title = "Title A"
          else if local title = "Title B"
    }
    But I get the error local not found.

  • #2
    Note the -if- following the -else- in the penultimate line of the code. Also, "outcome" is not properly referenced in the 2nd line of the code (missing right quotation mark).

    Code:
    foreach outcome in out_num out_can {
          if strpos("`outcome'","num")>0 local title = "Title A"
          else local title = "Title B"
    }
    At the end of the loop, the local title will correspond to the final outcome in the foreach list, i.e., "out_can". You probably need some intermediate display commands to know whether the earlier elements in the list satisfy the condition.

    Code:
    foreach outcome in out_num out_can {
          if strpos("`outcome'","num")>0 local title = "Title A"
          else local title = "Title B"
          display "For outcome `outcome', title= `title'"
    }

    Last edited by Andrew Musau; 22 May 2025, 15:54.

    Comment


    • #3
      There's actually another error too. Your code should read (note the closing single quote after outcome):

      Code:
      foreach outcome in out_num out_can {
            if strpos("`outcome'","num")>0 local title = "Title A"
            else local title = "Title B"
      }

      Comment


      • #4
        I'm confused why else if doesn't work in this case. If I use the following code it works.

        Code:
        foreach depvar in depvar1 depvar2 {
            if "`depvar'" == "depvar1" local spec = "original"
            else if "`depvar'" == "depvar2" local spec = "interacted"
        }

        Comment


        • #5
          This is a condition to be evaluated within an else command:

          else if "`depvar'" == "depvar2"
          whereas this is a command to do something.

          else local title = "Title B"
          Last edited by Andrew Musau; 22 May 2025, 16:05.

          Comment


          • #6
            Although the main example keeps changing, and it may be simplified out of a more complicated context, I cannot follow quite why a loop is being used here at all. In particular, in the corrected form

            Code:
             
             foreach outcome in out_num out_can {       if strpos("`outcome'","num")>0 local title = "Title A"       else local title = "Title B" }
            out_num is first used, but the assignment first time round is ignored: the loop will exit with a title based on the contents of out_can

            I would be happy to learn that the answers here are applicable to the associated real example.

            Comment

            Working...
            X