Join R data.tables where key values are not exactly equal--combine rows with closest times

前端 未结 2 984
谎友^
谎友^ 2020-11-30 06:57

Is there a slick way to join data tables in R where key values of time are close, but not exactly the same? For example, suppose I have a data table of results that are give

2条回答
  •  独厮守ぢ
    2020-11-30 07:28

    Another option may be roll='nearest' (new in v1.8.8 on CRAN).

    > setkey(DT1,x,time)
    > DT1
       x time v
    1: a   10 1
    2: a   30 2
    3: a   60 3
    4: b   10 4
    5: b   30 5
    6: b   60 6
    7: c   10 7
    8: c   30 8
    9: c   60 9
    > DT2
       x time
    1: a   17
    2: b   54
    3: c    3
    > DT1[DT2,roll="nearest"]
       x time v
    1: a   17 1
    2: b   54 6
    3: c    3 7
    

    Note that 17 appears to be closer to 10 than 30, hence the result in the first row.

    If you need to roll to the next observation (next observation carried backwards) :

    > DT1[DT2,roll=-Inf]
       x time v
    1: a   17 2
    2: b   54 6
    3: c    3 7
    

提交回复
热议问题