Announcement

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

  • Issues with AND/OR function with string variables

    Hi all,

    I'm having a bit of difficulty getting the AND/OR commands to work.

    The problem that I have is that the coding is shared across all variables (it's a set of product codes), but I want to link it to the original variable specified in that line of code. I've added part of the code below, and all of the codes (code1/2/3/4) are being linked with both product 1 and 2 - even though 1/2 are only mentioned alongside product1 (and the same problem with product2). How can I prevent this?

    Thanks,

    Calum

    gen newvar=0
    replace newvar=1 if product=="product1" & productcode=="code1" | lsoanum=="code2"
    replace newvar=1 if product=="product2" & productcode=="code3" | lsoanum=="code4"

  • #2
    I'm really not sure what you want to do here; I find your description of the problem extremely confusing. But if I have guessed correctly what you want, the difficulty here is due to the order of operations. In evaluating logical expressions in Stata (and most programming languages), & is applied before |. Consequently,
    Code:
    replace newvar=1 if product=="product1" & productcode=="code1" | lsoanum=="code2"
    is understood by Stata to mean
    Code:
    replace newvar=1 if (product=="product1" & productcode=="code1") | lsoanum=="code2"
    Consequently, in any observation where lsoanum == "code2", the | condition is satisfied regardless of what product and productcode are, so newvar is set to 1 for those observations. Same thing in the second line: whenever lsoanum == "code4", regardless of the values of product and productcode, newvar is set to 1. So I think what you need to do is force the ordering of observations to be different by using explicit parentheses:

    Code:
    replace newvar=1 if product=="product1" & (productcode=="code1" | lsoanum=="code2")
    replace newvar=1 if product=="product2" & (productcode=="code3" | lsoanum=="code4")
    As I say, I found your description rather confusing and I'm really just guessing at what you might have meant. If this isn't it, please post back. In addition to trying to explain more clearly, you probably should post some example data along with a hand worked example of the results you are hoping to get. If you do that, be sure to read FAQ #12 for instructions on how to post data examples in a helpful way, using the -dataex- command.

    By the way, and and or, in Stata, are neither commands nor functions. They are operators.

    Comment


    • #3
      Hi Clyde,

      Apologies for the unclear explanation. Nevertheless, you figured it out and the code at the bottom (with the correct use of the brackets) was exactly what I was looking to do. Thank you very much!

      Best,

      Calum

      Comment

      Working...
      X