Announcement

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

  • extremely LONG operator using "or"

    Hi
    There are 2 parts to my question. My 6 variables are x3006, x3007, x7513, x7514, x7515, x6848. I want to generate a new variable "have" if any of the 6 variables ==1,2,3,11,12,13,22,23,24,25 or 92. (it's an "or" statement)

    But the macro below did not return the right number. so I thought I'd create many lines of codes then combine them, but one of them is too long. Any advice on how to proceed?
    (A) Using macro
    gen have = .

    forvalues i = x3006/x3007/x7515/x7514/x7515/x6848 {

    replace have = 1 if inlist(x`i',1,2,3,11,12,13,22,23,24,25,92)

    }


    (B) So I thought I create each individual 6 variables i.e. have1, have2, have 3, have 4, have 5, have 6, then recode them to "have" if any of the have1-have6==1. However, one of the have is too long so it says syntax error. Is there a limit to how many "or"?

    gen have1=0
    replace have1 if x3006==23| x3007==23| x7513==23 |x7514==23 |x7515==23 |x6848==23 |x3006==24 |x3007==24 |x7513==24 |x7514==24 |x7515==24|x3006==25 |x3007==25|x7513==25|x7514==25 |x7515==25|x6848==25 |x3006==92 |x3007==92|x7513==92 |x7514==92 |x7515==92|x6848==92


    Thank you for your help.
    Lena

  • #2
    Hi lena,

    (A) I think you're looking for something like this:

    Code:
    gen have = 0
    foreach var in x3006 x3007 x7515 x7514 x7515 x6848 {
        replace have = 1 if inlist(`var',1,2,3,11,12,13,22,23,24,25,92)
    }
    (B) You need to set the replaced observations to something. There may be other syntax errors, that's just the one I see.

    Code:
    replace have1 = 1 if ...
    Please provide example data in the future. I can't test my code before sending it to you without example data.

    Comment


    • #3
      You could alternatively also use the egen command to accomplish this in one line of code:
      Code:
      egen byte have = anymatch(x3006 x3007 x7515 x7514 x7515 x6848), values(1/3 11/13 22/25 92)

      Comment


      • #4
        Not the main point, but this might be a little easier if you used less cryptic variable names.

        Otherwise my contribution here was to write the first version of anymatch() in 1999....
        Last edited by Nick Cox; 29 Oct 2022, 03:14.

        Comment


        • #5
          Coming back around to this today, I notice x7515 appears twice in the variable list you provide in your question code, and in the subsequent responses from myself and Hemanshu. I believe you will want to replace the first x7515 with x7513. I feel this particular mistake speaks to Nick's point about using less cryptic variable names.

          Comment


          • #6
            Thank you so much for your kindness and contribution. I appreciate it.
            Yours truly
            Lena

            Comment

            Working...
            X