如何检查来自df2的对是否在R中的df1对(包括对)?

问题描述 投票:1回答:2

我有两个数据帧,在这里我想将数据帧对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.

我已经在StackOverflow中完成了这里的工作,但这里没有列出:Check if column value is in between (range) of two other column values但是此人正在将单个值与成对进行比较,而不是将成对的成对或成对的成对进行比较。我对两个数据框都做了cbind,并使用它进行了比较。但是我失败了。

有人可以帮我还是给我一些指导。谢谢!

r dataframe comparison pairwise
2个回答
3
投票

我们可以使用mapplyotdf_2值与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>

0
投票

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

library(data.table)
setDT(df_2)[df_1, exists := "YES", on = .(o >= x, t < y), mult = 'first']
© www.soinside.com 2019 - 2024. All rights reserved.