Announcement

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

  • How to create a new binary variable (0-1) based on some conditions in Stata?

    input id t1 t2 t3
    1 1.5 1.4 1.6
    2 1.5 . 1.9
    3 . 2.0 1.6
    4 . . 2.2
    5 1.9 2.1 2
    6 1.8 2.0 1.9
    7 . . .
    end


    As suggested above, I want to create a new variable called sign.
    If t2>t1, then sign=1; if t2<=t1, then sign=0.
    Because t1 and t2 all have missing values, how can I keep missing values in the new variable "sign" in Stata?
    I think the rule is as long as there is a missing value in t1 or t2, then the variable "sign" should be missing value.
    Thanks for your Stata code!
    Last edited by smith Jason; 12 Jul 2021, 14:59.

  • #2
    up!

    Comment


    • #3
      This will probably do it, but do check in your full dataset:
      Code:
      . gen sign = .
      (7 missing values generated)
      
      . replace sign = 0 if t2<=t1 & !missing( t1)
      (1 real change made)
      
      
      . replace sign = 1 if t2>t1 & !missing( t2)
      (2 real changes made)

      Comment


      • #4
        Thank you!

        Comment


        • #5
          Bumping a post after 26 minutes is not good practice -- if that is what #2 is. We explain that already at #1 of https://www.statalist.org/forums/help#adviceextras


          Code:
          gen wanted = t2 > t1 if !missing(t1, t2)
          is another way to do it with less code.

          Comment


          • #6
            Thank you very much!

            Comment

            Working...
            X