Announcement

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

  • Merge if merge

    Hi,


    I have used the command "merge", creating a new var called "epr" instead of "_merge":

    merge m:1 id using "D:\Files\COST2020.dta",gen(epr)



    And I want to use "merge" again but just if epr==2, that's mean:

    merge m:1 id using "D:\Files\PW2020.dta", if epr==2



    Is that possibible with this software? I hope you can help me


    Kind Regards,
    S.




  • #2
    -merge- does not allow "if" (note that Stata does not put "if" after the comma, as you have it, anyway)

    however, you could always split the file into two, one for epr==2 and one for epr!=2, do your merge and then -append- the files

    Comment


    • #3
      You may also - preserve -, then - keep if epr==2- , finally use - merge - command.
      Best regards,

      Marcos

      Comment


      • #4
        I am assuming you intend that all the observations in the dataset after the first merge remain after the second merge, but only those with epr==2 have the values for the new variables from PW2020 appended, while observations with epr!=2 have missing values for those new variables. The key then is to save a copy of the id, then replace the id for epr!=2 with some value that does not appear in PW2020, do the merge, and then replace the id with the saved original values.

        So suppose your id variable is a positive integer, so that there is no observation with id==0. Then something like the following untested code would, I think, do what you need.
        Code:
        merge m:1 id using "D:\Files\COST2020.dta",gen(epr)
        clonevar save_id = id
        replace id = 0 if epr!=2
        merge m:1 id using "D:\Files\PW2020.dta"
        assert _merge ==1 if id==0
        replace id = save_id if id==0
        drop save_id
        Added as an afterthought: if the variables in PW2020 already appear in the dataset after the first merge and you want the values in PW2020 to replace the values already in the dataset, then you will want to use the update option and possibly the replace option on your merge command.

        Comment

        Working...
        X