Announcement

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

  • How to do a many-to-many merge/joinby, when each masterfile match should get all using datafile's matched rows

    Hi!
    Suppose I have two datafiles: datafileA and datafileB.
    Both datafiles have a variable called ID.
    In both datafiles ID does not uniquely identify observations:
    in datafileA, each occurence of a certain ID represents a case for that specific ID. There can be many cases for a specific ID.
    In datafileB, each occurence of a certain ID is accompanied by a year and info about that year for that specific ID. There can be many years for a specific ID.

    Now, each time an ID appears in datafileA (a case), I would like to copy this row as many times as that ID has observations (or years) in datafileB, and merge the matching rows.
    The results should be so that the datafileA row appears the same for each matched row in datafileB, which have altering content for each year.

    Is this a situation for many-to-many merge, or should I do a joinby to achieve this?
    I can always separate all duplicates from datafileA to their own datasets and do then a 1:m merge for each of them with datafileB, but I'm asking if a more straightforward solution exists.

    Thank you already in advance!


  • #2
    It seems that

    Code:
    clear
    use "datafileA"
    joinby ID using "datafileB"
    .. is doing exactly this. So situation solved. I will leave the topic here in case someone else searches for this in the future.

    *************************************
    EDIT:
    It seems that both datafiles must be first sorted by the key variables, in order for this to work properly.
    So:
    Code:
    clear
    use "datafileB.dta"
    sort ID
    save "datafileB.dta", replace
    
    clear
    use "datafileA"
    sort ID
    joinby ID using "datafileB"
    Last edited by Kasper Kotisaari; 23 Oct 2025, 05:13.

    Comment


    • #3
      Yes, you have arrived at the correct solution, and thank you for posting it so that others with a similar problem in the future can learn from it.

      Comment

      Working...
      X