R根据间隔和合并切割两个data.frames

geo*_*dex 1 r dataframe

如何根据间隔剪切两个数据帧并合并它们?

数据框1

read.table(textConnection(
"   from to Lith  
1   0   1.2 GRN   
2   1.2 5.0 GDI   
"), header=TRUE)    
Run Code Online (Sandbox Code Playgroud)

数据框2

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) 
Run Code Online (Sandbox Code Playgroud)

产生的数据框架

  from to Weath Lith 
1 0.0 1.1 HW  GRN
2 1.1 1.2 SW  GRN
3 1.2 2.9 SW  GDI
4 2.9 5.0 HW  GDI 
Run Code Online (Sandbox Code Playgroud)

edd*_*ddi 6

使用以下roll功能的好地方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
Run Code Online (Sandbox Code Playgroud)