比方说,我有2个数据帧,列的开始和结束无重复,按每个范围排序。例如:
df1:
start end
10 20
21 35
37 50
df2:
start end
12 15
17 19
22 24
26 29
31 40
43 46
我想基于df2
范围内的df1
范围的联接操作获得一个新的数据帧,如下所示:
range.df1 range.df2
10:20 12:15
10:20 17:19
21:35 22:24
21:35 26:29
21:35 31:35
37:50 37:40
37:50 43:46
有人可以告诉我如何在R中实现这一目标吗?
答案 0 :(得分:3)
这里是foverlaps
library(data.table)
setDT(df1, key = names(df1))
setDT(df2, key = names(df2))
foverlaps(df1, df2)[, .(range.df1 = paste(i.start, i.end, sep=":"),
range.df2 = paste(start, end, sep=":"))]
# range.df1 range.df2
#1: 10:20 12:15
#2: 10:20 17:19
#3: 21:35 22:24
#4: 21:35 26:29
#5: 21:35 31:40
#6: 37:50 31:40
#7: 37:50 43:46
df1 <- structure(list(start = c(10L, 21L, 37L), end = c(20L, 35L, 50L
)), class = "data.frame", row.names = c(NA, -3L))
df2 <- structure(list(start = c(12L, 17L, 22L, 26L, 31L, 43L), end = c(15L,
19L, 24L, 29L, 40L, 46L)), class = "data.frame", row.names = c(NA,
-6L))