MOL
MOL

Reputation: 11

Merge two data frames based on range value in R

Would it be possible to have a function that would consider having a range in the "by" argument of a joint?

Example:

#Table 1
  A B C D
1 a 1 10 15
2 a 11 1000 12.5
3 b 1 5 2
4 b 6 1000 1

#Table 2
  A B
1 a 53
2 b 3 

Joint Table:

  A B 1.D
1 a 53 12.5
2 b 3 2

Upvotes: 0

Views: 58

Answers (1)

IceCreamToucan
IceCreamToucan

Reputation: 28705

Looks like you want to update table 2 based on a rolling join with table 1 on A and B

library(data.table)
setDT(tb1)
setDT(tb2)

tb2[tb1, on = .(A, B), roll = -Inf, D := i.D]

This updates tb2 so now we have

tb2
#    A  B    D
# 1: a 53 12.5
# 2: b  3  2.0

Data used:

tb1 <- fread('
A B C D
 a 1 10 15
 a 11 1000 12.5
 b 1 5 2
 b 6 1000 1
')

tb2 <- fread('
  A B
 a 53
 b 3 
')

Upvotes: 1

Related Questions