Merge two datasets based on date ranges. R
A fast method is using foverlaps from data.table package, see ?data.table::foverlaps.
library(data.table)
stays&lt;-data.table(stays)
type&lt;-data.table(type)
setkeyv(type, c(&quot;Hospital&quot;, &quot;Room&quot;, &quot;StartDT&quot;, &quot;EndDT&quot;))
foverlaps(stays, type, by.x=c(&quot;Hospital&quot;, &quot;Room&quot;, &quot;StartDate&quot;, &quot;EndDate&quot;))

   Hospital Room      Type    StartDT      EndDT PatientID           StartDate             EndDate
1:     ODCC  4SW      &lt;NA&gt;       &lt;NA&gt;       &lt;NA&gt;       101 2020-06-04 16:21:47 2020-06-22 15:12:39
2:     ODCC   1W       ICU 2020-06-01 2020-07-30       101 2020-06-22 15:12:40 2020-09-08 14:03:34
3:     ODCC   1W Emergency 2020-08-01 2021-05-12       101 2020-06-22 15:12:40 2020-09-08 14:03:34
4:     ODCC   1N      &lt;NA&gt;       &lt;NA&gt;       &lt;NA&gt;       101 2020-09-08 14:03:35 2020-10-02 06:50:24
5:     ODCC   1W Emergency 2020-08-01 2021-05-12       101 2020-10-02 06:50:25 2020-10-05 14:25:54

```