使用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_1应该是:
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
下图应该有助于可视化df_2中16个比较区域中每个区域的位置。
任何帮助是极大的赞赏。
您可以使用purrr::map2
(或base::mapply
,如果您愿意)迭代x
和y
值,将每个集合与df_2
中的最小值和最大值进行比较,并将结果用于子集df_2$region
:
library(tidyverse)
set.seed(806)
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 <- 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_1 %>%
mutate(region = map2_int(x, y,
~df_2$region[.x > df_2$xmin &
.x <= df_2$xmax &
.y > df_2$ymin &
.y <= df_2$ymax]))
#> # A tibble: 5 x 3
#> region x y
#> <int> <dbl> <dbl>
#> 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