Join dataframes by id and overlapping date range

前端 未结 3 575
暗喜
暗喜 2021-01-15 15:34

I have two dataframes x and y that contain columns for ids and for dates.

id.x <- c(1, 2, 4, 5, 7, 8, 10)
date.x <- as.Date(c(\"2015-01-01\", \"201         


        
3条回答
  •  臣服心动
    2021-01-15 16:13

    Using inner join of y and x data tables by setting the keys to id of both datatables, and then checking for date conditions, and finally extract the true ones.

    library("data.table")
    
    x <- as.data.table(x)
    
    y <- as.data.table(y)
    
    setkey(x, id.x)
    
    setkey(y, id.y)
    
    z <- y[x, nomatch = 0][, j = .(is_true = ((date.y <= date.x + 3) & (date.y > date.x)), id.y, date.x, date.y)][i = is_true == TRUE]
    
    > z
       is_true id.y     date.x     date.y
    1:    TRUE    1 2015-01-01 2015-01-03
    

提交回复
热议问题