【问题标题】:Populate New Column Based on Conditional Match in Another Data Frame in R根据 R 中另一个数据框中的条件匹配填充新列
【发布时间】:2018-01-27 05:03:21
【问题描述】:

使用 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 个比较区域中每个区域的位置。

非常感谢任何帮助。

【问题讨论】:

  • 我得到了library(tidyverse); df_1 %&gt;% mutate(region = map2_int(x, y, ~df_2$region[.x &gt; df_2$xmin &amp; .x &lt;= df_2$xmax &amp; .y &gt; df_2$ymin &amp; .y &lt;= df_2$ymax]))的答案,但地区不同。
  • @alistaire 您的代码似乎按预期工作。我认为这些区域在示例数据集中被错误标记。

标签: r dplyr apply


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-10
    • 2016-02-14
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多