Announcement

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

  • if condition with multiple values+

    I want to create a binary variable which takes a value if a condition is met.

    Say I want do the following
    Code:
     
    gen OilExp = 1 if Country isanyoffollowing("Algeria","Bahrain","Iran","Iraq" ,"Kuwait","Oman", "Qatar","Saudi Arabia","Syria","United Arab Emirates")
    my command is as below
    Code:
     
    gen OilExp = cond(inlist(Country, "Algeria","Bahrain","Iran","Iraq","Kuwait","Om an", "Qatar","Saudi Arabia","Syria","United Arab Emirates"), 1, 0)
    or
    ​​​​​​​
    Code:
     
    gen OilExp = 1 if inlist(Country, "Algeria","Bahrain","Iran","Iraq","Kuwait","Om an", "Qatar","Saudi Arabia","Syria","United Arab Emirates")
    replace OilExp = 0 if OilExp == .
    However, I get the error "expression too long" for both commands

    But when I reduce the number of countries in the list it works. Is there a command that would handle this condition when there are many matching criteria?
    Last edited by Joao Macosso; 17 Jan 2023, 11:23.

  • #2
    there is no question but here is my guess: inlist, when used with strings, is limited to fewer values than you show; you need to break your command into 2 pieces and place an "or" between them; see
    Code:
    h inlist()

    Comment


    • #3
      And your question is....???

      Not knowing what you are asking, I'll just comment on a few things I see:

      1. When working with string variables, -inlist()- allows a maximum of 10 arguments. You have 11. So you need to either -encode- the country variable to get a numeric variable, and then use the numeric variable and the corresponding numeric codes in your -inlist()- expression, or, you can break the condition up into two parts:
      Code:
      gen OilExp = cond(inlist(Country, "Algeria","Bahrain","Iran","Iraq","Kuwait") ///
          | inlist(Country, "Oman", "Qatar","Saudi Arabia","Syria","United Arab Emirates"), 1, 0)
      2. It is never necessary to code
      Code:
      gen logical_variable = cond(logical_expression, 1, 0)
      because you can get the identical result more simply with just
      Code:
      gen logical_variable = logical_expression
      Added: Crossed with #2.

      Comment


      • #4
        Also the user written

        Code:
        . findit inlist2
        can be useful here.

        Comment

        Working...
        X