答案 0 :(得分:0)
您可以使用purrr::map2
(或base::mapply
,如果您愿意)迭代x
和y
值,将每个集合与df_2
中的最小值和最大值进行比较{1}}并将结果用于子集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