r - 如何检查 df2 中的对是否与 R 中的 df1 (包括)成对?

标签 r dataframe comparison pairwise

我有两个数据帧,我想将数据帧对 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 并使用它进行比较。但我失败了。

接下来我可以尝试什么?

最佳答案

我们可以使用 mapplydf_2df_1ot 值进行比较code> 并检查任何值是否在范围内,并相应地分配“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>

关于r - 如何检查 df2 中的对是否与 R 中的 df1 (包括)成对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60584096/

相关文章:

mysql - 需要帮助优化比较两个表的 mysql 查询

r - R 中带有子集的 For 循环

在 R 中读取二进制光栅文件

r - 在 3 维数组上向量化 R 中的嵌套循环

r - 如何根据列中的信息重命名行名的子集?

python - 需要帮助从 pandas 数据框中过滤前 3 个计数

python - 两个列表,在 python 中比较更快

`glmnet` 的岭回归给出的系数与我通过 "textbook definition"计算的不同?

python-3.x - 每次满足特定条件时,如何找到行之间的最高值?

c++ - C++20 概念 bool 可测试的奥秘