簡體   English   中英

根據 +/- 3 個月內的日期,在 R 中使用 data.table package 連接兩個數據框

[英]Join two data frames using the data.table package in R based on dates that are within +/- 3 months

我正在嘗試加入兩個數據框; 按 ID,使用 R 中的 data.table package 以及潤滑日期 ZEFE070A8E603E8ZF6A 中的 ZEFE970A8E603E8ZF6。 我只想加入在 Date1 之前或之后 3 個月的 Date2 行

df1

ID 日期1
1 2019-09-09
2 2019-09-09
3 2019-09-09
4 2019-09-09

Df2

ID 日期 2 價值
1 2020-09-09 6
1 2019-10-09 7
2 2019-03-13 8
4 2019-10-27 15

我想要的最終數據框

ID 日期1 ID 日期 2 價值
1 2019-09-09 1 2020-09-09 6
2 2019-09-09 2 不適用 不適用
3 2019-09-09 不適用 不適用 不適用
4 2019-09-09 4 2019-10-27 15

我在下面包含了我的代碼。 我收到錯誤說不需要滾動后的 =,但我認為它是必需的。

library(data.table)
library(lubridate)

df1 <- data.table(ID = seq_len(4L),
                  Date1 = as.Date("2019-09-09"))

df2 <- data.table(Id = c(1L, 1L, 2L, 4L),
                  Date2 = as.Date(c("2020-09-09","2019-10-09","2019-03-13","2019-10-27")),
                  Value = c(6L, 7L, 8L, 15L))


df2[, Date1Copy := Date2]  
df2[, IDcopy := Id] 
setkey(df2, ID, Date2)    ## set the column to perform the join on
setkey(df, ID, Date1) 
test = df1[df2, rollends = if (roll=="nearest") c(TRUE,TRUE)
           else if (roll = as.Date(Date1)%m+% months(3)|roll = as.Date(Date1)%m-% months(3)) c(FALSE,TRUE)
           else c(TRUE,FALSE)]```

data.table中的滾動連接非常有用,但可能有點難以掌握。 rollends的語法與您那里的語法有很大不同,它不是為處理任何類型的復雜邏輯而設計的,只是簡單的TRUE / FALSE情況。

無論如何,這是解決這個問題的一種方法。 使用月份算術作為過濾標准並結合nearest值要求使得這是一個多步問題,而不是一步連接(至少我能看到它的任何方式)

雖然連接/過濾/復制結果值操作在技術上是單行的,但我盡我所能添加了大量對嵌套操作的解釋。

## Make a copy of Date2 to use as key, as it will be inaccessible within the joined table
df2[, Date2Copy := Date2]

## Set Keys
setkey(df1,ID,Date1)
setkey(df2,Id,Date2Copy)

## Step 3: (read the inner nested steps first!)
## After performing the steps 1/2, join the intermediate result table back to `df1`...
df1[
  ## Step 1:
  ## First use the key of `df1` to subset `df2`` with a rolling join
  df2[df1,.(ID, Date1, Date2), roll = "nearest"
      ## Step 2:
      ## Then apply the +/- 3 month filtering critera
      ][between(Date2,
                Date1 %m-% months(3),
                Date1 %m+% months(3))]
  ## Step 3:
  ## ...on the `ID` column and add the intermediate results
  ## for `Date2` and `Value` columns to `df1` by reference
  , c("Date2","Value") := .(i.Date2,i.Value), on = .(ID)]
     
## Results    
print(df1)
#    ID      Date1      Date2 Value
# 1:  1 2019-09-09 2019-10-09     7
# 2:  2 2019-09-09       <NA>    NA
# 3:  3 2019-09-09       <NA>    NA
# 4:  4 2019-09-09 2019-10-27    15

這些是我用於滾動連接的三個首選資源(package 文檔除外),它們都幫助我理解了多年來在多個方面的一些怪癖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM