Announcement

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

  • generating variables with "or"

    Hi, I wish to create a new variable given certain parameters of 3 other variables.
    I have tried the basic creation of a new variable commands "gen highscore = . / replace highscore = 0 if (varA <1)
    [I can get that far, but what I need is something essentially like the following - but the syntax doesn't work):

    replace highscore = 0 if (varA <=1) or if (varB <=10) or if (varC >= 10)

    Is there a way to fix this syntax?

    Thanks for any and all help - I am sure the answer is pretty straightforward.

  • #2
    To learn about the use of logical operators in Stata, see -help operators-, which among things will show you the symbols for the logical operators and, or, and not. You want something like:
    Code:
    replace highscore = 0 if (varA <=1) | (varB<=10) | (varC >=10)
    You may also in similar contexts find the -cond()- function of interest, by which Stata implements what some other languages do with if-then.

    Comment


    • #3
      Perhaps this would be more direct still


      Code:
      gen highscore = (varA > 1) | (varB > 10) 
      where you should add what makes sense for varC (at present the implication is that varC >= 10 is not a high score).

      For more discussion, see

      https://www.stata.com/support/faqs/d...mmy-variables/

      https://www.stata.com/support/faqs/d...rue-and-false/

      https://www.stata-journal.com/articl...article=dm0099

      Comment


      • #4
        Even for such trivial questions it is better if one provides a data sample with dataex, so that the discussion can proceed with an exact solution, rather than abstract metaphors.

        Apart from the excellent advice Mike gives, here is something that has struck me over and over again: Both beginning and intermediate Stata users underestimate the ability of Stata to evaluate logical conditions. This ability most of the time leads to one line solutions.

        Here is an example, say I want to generate a dummy which is 1 if a car is foreign and rep78 is 3, say. I can do it in one shot:

        Code:
        . sysuse auto, clear
        (1978 Automobile Data)
        
        . gen dummy = foreign==1 & rep==3
        This above will generate 0s when rep is missing, which might, or might not be what we want. If we want to have this missing if any of the variables involved are missing, we can again have a one shot solution:

        Code:
        . gen dummywithmissing = foreign==1 & rep==3 if !missing(foreign,rep)
        (5 missing values generated)


        Comment

        Working...
        X