Announcement

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

  • Within groups, copy value of existing var into new var if condition applies.

    Dear Statalist,
    I have a dataset with the following structure: Individuals gave answers about how decisions were made within their household. In this example, the question was regarding household expenditures (hhexp) where they could choose between 4 answer options. Also, I have the existing variable icshare in the dataset.
    hh_id ind_id hhexp icshare newvar
    1 11 1 0 0
    1 12 1 1 0
    2 21 2 0 0
    2 22 4 0.5 0.5
    2 23 2 0.5 0.5
    3 31 1 1 0
    4 41 1 0.25 0.25
    4 42 3 0.25 0.25
    4 43 4 0.4 0.4
    4 44 1 0.1 0.1
    I am looking for a way to copy the values of the existing variable icshare into a newvar if a certain condition (hhexp=4) is met within a group, that is the household (hh_id).

    bysort hh_id: assign their respective values of icshare to the household members in newvar if hhexp=4;
    bysort hh_id: assign newvar == 0 if hhexp~=4.

    The result of newvar should look like in the above example.

    I can think of a straightforward solution for the individuals that actually gave the answer hhexp=4, but I am at a loss when it comes to the groupwise identification.
    Do you have any ideas? Any help would be greatly appreciated!
    Cheers,
    Laura
    Last edited by Laura Zoch; 30 Mar 2017, 07:51.

  • #2
    Code:
    bys hh_id: egen max_hhexp_byid=max(hhexp)

    Comment


    • #3
      Hi Jorrit,
      thanks for your suggestion. It is good code, but it doesn't exactly produce what I wanted, since the new variable records the value of hhex, but not icshare.
      I think, using a rather not so elegant way, I've figured out how to get my intended newvar (I'm using -foreach- since I have more than one decision category eventually):

      foreach v in hhexp {
      gen `v'_4=1 if `v'==4
      bysort hh_id : replace `v'_4 = `v'_4[1]
      replace `v'_4=icshare if `v'_4==1
      replace `v'_4=0 if `v'_4==.
      }
      Cheers!
      Laura

      Comment


      • #4
        Ah, I was a bit lazy with that post but I thought you'd figure it out from there. You need to add some create and replace statement like:
        Code:
        bys hh_id: egen max_hhexp_byid=max(hhexp)
        gen newvar2=0
        replace newvar2 = icshare if max_hhexp_byid==4
        Simple. No loops needed here

        Comment

        Working...
        X