Announcement

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

  • If statements on multiple values of a variable

    Hello

    I have generated a variable Group=. and I would like to replace Group=="garden" if id equals 1, 5, 7, 12, 13, or 15 and Group=="control" if id equals 2, 3, 6, 8, 9, or 14. Could someone please let me know the easiest way to write if statements other than listing out every value of my variable id? I come across things like this a lot in my work so I'm looking for a solution that broadly apply to similar situations.

    Thanks!

  • #2
    Given that your two number series don't have any obvious pattern, I don't think there is any alternative to listing them. Probably the most typographically simple way to accomplish this is:

    Code:
    gen Group = "garden" if inlist(id, 1, 5, 7, 12, 13, 15)
    replace Group = "control" if inlist(id, 2, 3, 6, 8, 9, 14)

    Comment


    • #3
      If those are all of the identifiers there are, this is also possible

      Code:
      gen Group = cond(inlist(id, 1, 5, 7, 12, 13, 15), "garden", "control")
      or, naturally, the other way round. Some people find the more explicit syntax that Clyde gave to be clearer, and that's fine by me too.

      Comment


      • #4
        The inlist was what I was missing, I was trying to find an alternative to replace if id==1; replace if id==3, etc. So this is perfect. Many thanks.

        Comment


        • #5
          FWIW, the reason I used both a -gen- and -replace- in this example is because I noticed that 4, 10, and 11 don't occur in either list. Now maybe they don't occur in the data either--we don't have that information. But I though it safer to assume that their omission was deliberate and that those numbers should not be associated with either value of Group. If I knew that the two lists were exhaustive of the possibilities, I would have recommended the same solution Nick did.

          Comment

          Working...
          X