基于R中另一个数据帧中的条件匹配填充新列

基于R中另一个数据帧中的条件匹配填充新列,r,dplyr,apply,R,Dplyr,Apply,使用dplyr、apply和/或ifelse语句,我想确定df_1的每对x和y坐标是否在df_2的一系列唯一xmin&xmax和ymin&ymax坐标之间。对于每个成功的匹配或“命中”,我想用相应的df_2$region标签填充一个新列df_1$region 例如: set.seed(806) # df_1 df_1 <- data.frame( region= 0, x = sample(seq(-2, 2, .05), 5, replace = TRUE), y = s

使用dplyr、apply和/或ifelse语句,我想确定df_1的每对x和y坐标是否在df_2的一系列唯一xmin&xmax和ymin&ymax坐标之间。对于每个成功的匹配或“命中”,我想用相应的df_2$region标签填充一个新列df_1$region

例如:

set.seed(806)
# df_1
df_1 <- data.frame(
  region= 0, 
  x = sample(seq(-2, 2, .05), 5, replace = TRUE), 
  y = sample(seq(0.5, 4.5, .05), 5, replace = TRUE))

# df_2
df_2 <- data.frame(
region = sample(1:16, 16),
xmin = rep(seq(-2, 1, 1), each = 4),
xmax = rep(seq(-1, 2, 1), each = 4),
ymin = rep(seq(0.5, 3.5, 1), times = 4),
ymax = rep(seq(1.5, 4.5, 1), times = 4))
下图有助于直观显示df_2中16个比较区域中每个区域的位置


非常感谢您的帮助。

您可以使用
purr::map2
(或者
base::mappy
,如果愿意的话)迭代
x
y
值,将每组值与
df_2
中的最小值和最大值进行比较,并将结果用于子集
df_2$区域

库(tidyverse)
种子集(806)
df_1 df_2$xmin和
.x df_2$ymin和
.y#A tibble:5 x 3
#>区域x-y
#>       
#> 1     16 -1.00  0.600
#> 2     12  0.950 1.55 
#> 3     16 -1.30  1.00 
#> 4      8 -1.40  3.05 
#> 5      9  1.25  4.50

我通过
库(tidyverse)得到了答案;df_1%>%mutate(region=map2_int(x,y,~df_2$region[.x>df_2$xmin&.x df_2$ymin&.y@alistaire)您的代码似乎按预期工作。我认为示例数据集中的区域标记错误。
region     x    y
    13 -1.00 0.60
    11  0.95 1.55
    13 -1.30 1.00
    5  -1.40 3.05
    4   1.25 4.50