比较两个数据帧的值并合并

时间:2017-02-15 14:51:15

标签: r dataframe merge

我正在使用R中的两个数据框:

df1 = data.frame(c("A", "B"), c(1, 21), c(17, 29))
colnames(df1) = c("location", "start", "stop")

df1
location    start    stop
A           1        17
B           21       29

df2 = data.frame(c("A", "A", "A", "A", "B"), c(1, 10, 20, 40, 20), c(10, 20, 30, 50, 30), c("x1", "x2","x4", "x5", "x3"))
colnames(df2) = c("location", "start", "stop", "out")

df2
location    start    stop   out
A           1        10     x1
A           10       20     x2
A           20       30     x4
A           40       50     x5  
B           20       30     x3

现在我想检查df1的每一行:

  • ' location'之间是否匹配?位于'位置'来自df2
  • 如果'开始'值是在df2的开始和结束范围内,或者如果'结束'值是在df2的开始和停止范围内,然后是相应的' out'来自df2的值应粘贴在df1
  • 的新列中

这是本例

的输出结果
df1_new

location    start    stop    out
A           1        17      x1,x2
B           21       29      x3

我已经开始使用R了,但是我已经陷入了需要查看df2完整数据框的位置

for (i in nrow(df1)) {
   if(df1$location[i] == df2$location # it needs to look for a match in the complete dataframe of df2. I don't know how to do this
   & if (df1$start[i] %in% # it needs to check if the start value lies in the range between df2$start & df2$end
}

2 个答案:

答案 0 :(得分:2)

首先需要aggregate,然后merge,即

merge(df1, aggregate(out ~ location, df2, toString), by = 'location')

#  location start stop    out
#1        A     1   17 x1, x2
#2        B    21   29     x3

答案 1 :(得分:2)

这是一种data.table方式,使用foverlaps

library(data.table)
setkey(setDT(df1))
setDT(df2, key = names(df1))

foverlaps(df1, df2)[, .(out = toString(out)), by=location]

#    location    out
# 1:        A x1, x2
# 2:        B     x3

如果需要,您可以从foverlaps结果中获取其他cols:

foverlaps(df1, df2)
#    location start stop out i.start i.stop
# 1:        A     1   10  x1       1     17
# 2:        A    10   20  x2       1     17
# 3:        B    20   30  x3      21     29