【问题标题】:How to check if pairs from df2 are in pairs of df1 (inclusive) in R?如何检查来自 df2 的对是否在 R 中成对的 df1(包括)?
【发布时间】:2020-03-08 02:53:24
【问题描述】:

我有两个数据帧,我想将数据帧对 b 与数据帧对 a 进行比较,并查看来自 b 的对是否在(包括)这些对/范围内在a。例如,见下文:

df_1 <- data.frame(x= c(-82.38319, -82.38318, -82.40397, -82.40417, -82.40423), 
                y= c(29.61212, 29.61125, 29.61130, 29.61134, 29.61167))
#Output:
#       x        y
# 1 -82.38319 29.61212
# 2 -82.38318 29.61125
# 3 -82.40397 29.61130
# 4 -82.40417 29.61134
# 5 -82.40423 29.61167

df_2 <- data.frame(o= c(-82.38320,-82.38317,-82.40397,-82.40416,-82.40424), 
                t= c(29.61212, 29.6114, 29.61130, 29.61133, 29.61167))
#Output:
#        o        t
# 1 -82.38320 29.61212
# 2 -82.38317 29.61140
# 3 -82.40397 29.61130
# 4 -82.40416 29.61133
# 5 -82.40424 29.61167

#made this dataframe as an example only.
desired_output <- data.frame(lat= df_2$o, lon= df_2$t, exists= c(NA, "YES","YES","YES",NA))
#Output I seek:
#       lat      lon    exists
# 1 -82.38320 29.61212   <NA> 
# 2 -82.38317 29.61140    YES
# 3 -82.40397 29.61130    YES
# 4 -82.40416 29.61133    YES
# 5 -82.40424 29.61167   <NA>

#explanation:
#1- even though 82.38320 is OK & is in rows 3,4,5 in df_1, 29.61212 is out of bounds with their co-pairings.
#2- row 2 of df_2 is within the row 5 of df_1.
#3- row 3 of df_2 matches to row 3 of df_1 thus inclusive
#4- row 4 pair matches and its co_pair is less than those pair of row 4 in df_1
#5- This pair at row 5 is out of bounds in all of the rows of df_1

#Column "exists" can be appended to dataframe b, result matters only, neatness is not an issue.

我已经在 Stack Overflow 中四处挖掘,除了 this listing 什么都没有。但是这个人将单个值与成对进行比较,而不是成对与成对或成对内的成对进行比较。我已经对两个数据框完成了cbind 并使用它进行了比较。但我失败了。

接下来我可以尝试什么?

【问题讨论】:

  • 比较规则是什么?为什么第 2 行是“YES”而第 1 行是 NA。
  • 谢谢 Ronak,规则是数据帧 df_2 中的 (a2,b2) 必须小于 a1 和 b1 或等于 a1 和 b1 或 (a2,b2) 中的任何一个实体对可以相等,但它的共同对必须匹配,或者必须从数据帧 df_1 的对中变小。我的术语有点弱,我可以进一步解释。之所以 2 是 YES,是因为 df_2 的第 2 对都小于 df_1 的第 5 对(因此在里面)。 df_2 的第 1 对是 NA,因为它不符合我提到的标准。含义 (a2,b2) 是不匹配的,并且它的配对之一超出了界限。抱歉修改。

标签: r dataframe comparison pairwise


【解决方案1】:

我们可以使用mapplydf_2ot 值与df_1 进行比较,并检查any 值是否为范围并相应地分配"YES"NA

df_2$exists <- c(NA, "YES")[mapply(function(x, y) 
                            any(df_1$x <= x & df_1$y >= y), df_2$o, df_2$t) + 1]

df_2
#           o        t exists
#1 -82.38320 29.61212   <NA>
#2 -82.38317 29.61140    YES
#3 -82.40397 29.61130    YES
#4 -82.40416 29.61133    YES
#5 -82.40424 29.61167   <NA>

【讨论】:

  • 先生,您真棒。谢谢你。我本来打算做一个可怕的 for 循环 C++ 风格,你救了我。
【解决方案2】:

我们可以在data.table中使用非等连接

library(data.table)
setDT(df_2)[df_1, exists := "YES", on = .(o >= x, t < y), mult = 'first']

【讨论】:

  • 谢谢 Akrun,也感谢您的意见。你的答案同样好:)
猜你喜欢
  • 2020-08-10
  • 2016-02-15
  • 2021-11-04
  • 2019-07-06
  • 2014-09-06
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多