Announcement

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

  • How can I use if command more efficiently to select cases among 15 consecutive variables?

    Hi everyone,

    I am working on a large database. The database has up to 15 variables for diagnosis of the disease. They are called DX1, DX2, DX3, etc. I want to select my cases based on certain diagnosis (let's say the diagnosis code for my cases is 275). This is what I was doing:

    generate MyCases=0
    replace MyCases=1 if DX1=="275" | DX2="275" | DX3="275" | DX ..... | DX15="275"

    I am kinda sure that there is a better and smarter way of selecting (replacing) the cases but I don't know how to do it. Also, I tried using the * after the variable as follows:

    generate MyCases=0
    replace MyCases=1 if DX*=="275"

    but the above command gives me an error: DX ambiguous abbreviation

    I appreciate if anyone knows a faster/more efficient way of doing this.

    Thanks,
    Reza

  • #2
    Wildcards won't work in that way:

    Note that this will work:

    Code:
    gen mycases = inlist("275", DX1, DX2, DX3)
    where you can extend the list of arguments to include 10 such variables, but not all 15. So I wouldn't do it like that, even though you could split the problem into 10 and 5 variables, because it is so tedious to type out such syntax. I would do it as a loop:

    Code:
    gen mycases = 0
    
    quietly forval j = 1/15 {
          replace mycases = 1 if DX`j' == "275"
    }
    If your values are all numeric, check out various egen functions.
    Last edited by Nick Cox; 16 Nov 2015, 13:52.

    Comment


    • #3
      Originally posted by Nick Cox View Post
      Wildcards won't work in that way:

      Note that this will work:

      Code:
      gen mycases = inlist("275", DX1, DX2, DX3)
      where you can extend the list of arguments to include 10 such variables, but not all 15. So I wouldn't do it like that, even though you could split the problem into 10 and 5 variables, because it is so tedious to type out such syntax. I would do it as a loop:

      Code:
      gen mycases = 0
      
      quietly forval j = 1/15 {
      replace mycases = 1 if DX`j' == "275"
      }
      Thank you so much, Nick! The loop solution makes my work much faster! Thanks again!

      Comment

      Working...
      X