R基于间隔和合并来切割两个数据 [英] R cutting two data.frames based on intervals and merging

查看:216
本文介绍了R基于间隔和合并来切割两个数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何根据间隔切割两个数据帧并合并?

How do I cut two data frames based on their intervals and merge them?

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



数据框2



Data Frame 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) 



结果数据框架



Resulting Data Frame

  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 


推荐答案

使用卷的好地方 data.table

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

这篇关于R基于间隔和合并来切割两个数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆