Announcement

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

  • Grouping Variable by combining two metric variables

    Hi there,

    I'd like to create a grouping variable "category" from a combination of two other metric variables (let's say "var1" and "var2").
    The categories shall be:

    category 1 = var1<50 AND var2<25
    category 2 = var1<50 AND var2>25
    category 3 = var1>50 AND var2<25
    category 4 = var1>50 AND var2>25

    How do I do this in STATA?
    I tried to use "egen" and "cut", but this works only with one source variable, doesn't?

    Thanks in advance,

    Philipp

  • #2
    Philip:
    welcome to this forum.
    Perhaps it is s -group- from -egen- what you're looking for.
    Kind regards,
    Carlo
    (StataNow 18.5)

    Comment


    • #3
      try using the "gen" command. example:

      Code:
      clear all
      sysuse auto
      
      gen category = .
      replace category = 1 if price < 5000 & weight < 2500
      replace category = 2 if price < 5000 & weight > 2500
      replace category = 3 if price > 5000 & weight < 2500
      replace category = 4 if price > 5000 & weight > 2500


      Comment


      • #4
        Thank you a lot, Carlo!
        It worked... :-)))

        Comment


        • #5
          Guest - Thank you, too! This looks nice!
          Last edited by sladmin; 19 Nov 2024, 08:37. Reason: anonymize original poster

          Comment


          • #6
            As a twist on #3 from Guest note also

            Code:
            sysuse auto, clear
            
            gen category = .
            replace category = 1 if price < 5000 & weight < 2500
            replace category = 2 if price < 5000 & weight > 2500
            replace category = 3 if price > 5000 & weight < 2500
            replace category = 4 if price > 5000 & weight > 2500
            
            gen category2 = 1 + (weight >= 2500) + 2 * (price >= 5000)
            
            assert category == category2
            The new code takes care of one possible nuance, values exactly equal to the thresholds.

            In addition, you need an extra qualifier


            Code:
            ... if !missing(weight, price)
            if there are missing values.
            Last edited by sladmin; 19 Nov 2024, 08:36. Reason: anonymize original poster

            Comment

            Working...
            X