Announcement

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

  • Using inlist or loop to generate new variable

    What is the most efficient way to do something like:

    gen newvar = 1 if v1 == 1 | v2 == 1 | v3 == 1 | v4 == 1 | v5 == 1 | v6 == 1 | v7 == 1

    I tried a foreach loop, but what I really am looking for is something like a "for any" loop. I also tried -inlist- but was not successful with that.

  • #2
    you don't show exactly what you tried or provide a -dataex- example, but try the following:
    Code:
    gen byte newvar=inlist(1,v1,v2,v3,v4,v5,v6,v7)

    Comment


    • #3
      Thanks, Rich Goldstein. Added in a "1 if" to your code and it worked perfectly--my syntax was just slightly off in my first attempt. Thank you.

      Comment


      • #4
        Added in a "1 if" to your code and it worked perfectly
        You created newvar as a variable which is 1 if the condition is fulfilled and is missing (.) otherwise.

        Rich created newvar as a variable which is 1 if the condition is fulfilled and is 0 otherwise.

        Most experienced Stata users would consider Rich's newvar more perfect than yours.

        For example, if you include your newvar as an independent variable in a regression, all the observations for which newvar is missing will be dropped, and then the variable will be dropped from the model because it is a constant 1.

        Comment


        • #5
          See also

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

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

          for lengthier treatments which include the point made implicitly by Rich Goldstein and explicitly by William Lisowski

          Comment

          Working...
          X