Good place to use the roll
feature of data.table
:
library(data.table)
dt1 = data.table(read.table(textConnection(
" from to Lith
1 0 1.2 GRN
2 1.2 5.0 GDI
"), header=TRUE))
dt2 = data.table(read.table(textConnection(
" from to Weath
1 0 1.1 HW
2 1.1 2.9 SW
3 2.9 5.0 HW
"), header=TRUE))
# set the key for the join
setkey(dt1, from)
setkey(dt2, from)
# get the unique id's
ids = sort(unique(c(dt1$from, dt2$from, dt1$to, dt2$to)))
# make a table of final from-to, keyed by 'final.from'
from.to = data.table(final.from = head(ids, -1),
final.to = tail(ids, -1),
key = 'final.from')
# join with a roll and combine together
result = dt1[from.to, roll = Inf][, Weath := dt2[from.to, roll = Inf]$Weath][,
`:=`(to = final.to, final.to = NULL)]
# from to Lith Weath
#1: 0.0 1.1 GRN HW
#2: 1.1 1.2 GRN SW
#3: 1.2 2.9 GDI SW
#4: 2.9 5.0 GDI HW