Announcement

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

  • Generate a Dummy variable with group

    Hello my data has 2 variables. I want to generate a dummy variable if there is something in A (=1) and nothing in A(=0) within the group B. my data looks like this (with how I want my dummy generated).
    A B Dummy
    Tom Group1 1
    Group1 1
    Group2 0
    Carl Group3 1



    I used the code

    gen dummy =!missing(A), group(B)

    but it says group ()not allowed please help. Thanks
    Last edited by Alex Carr; 13 May 2017, 11:42.

  • #2
    Hi Alex,

    This is a bit of a tedious solution (I admit), but does the job:

    Code:
    gen dummy = 1 if A!=""
    bysort B: carryforward dummy, replace //if you don't have this installed type - ssc install carryforward - 
    replace dummy = 0 if dummy==.
    The first line assumes variable A is a string. In the future, do please share data on Statalist using dataex (ssc install dataex). Tables are not convenient for replication

    Comment


    • #3
      I will start by reminding you of the advice you received on your previous post. Please review the Statalist FAQ linked to from the top of the page, as well as from the Advice on Posting link on the page you used to create your post. See especially sections 9-12 on how to best pose your question. It's particularly helpful to use the dataex command to provide sample data, as described in section 12 of the FAQ.

      With that said, perhaps the following will point you in a helpful direction.
      Code:
      * Example generated by -dataex-. To install: ssc install dataex
      clear
      input str4 a str6 b
      "Tom"  "Group1"
      ""     "Group1"
      ""     "Group2"
      "Carl" "Group3"
      end
      by b, sort : egen Dummy = max(!missing(a))
      list, sepby(b)
      Code:
      . list, sepby(b)
      
           +-----------------------+
           |    a        b   Dummy |
           |-----------------------|
        1. |  Tom   Group1       1 |
        2. |        Group1       1 |
           |-----------------------|
        3. |        Group2       0 |
           |-----------------------|
        4. | Carl   Group3       1 |
           +-----------------------+

      Comment


      • #4
        Thanks for sharing the code!

        Comment


        • #5
          Another way to do it:

          Code:
          bysort b (a) : gen indicator = !missing(a[_N])

          Comment


          • #6
            Originally posted by Nick Cox View Post
            Another way to do it:

            Code:
            bysort b (a) : gen indicator = !missing(a[_N])
            Thank you again Nick. You are a life saver

            Comment

            Working...
            X