如何使用前缀作为匹配来连接数据帧?

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

假设我有这些数据:

data <- tibble(
  x = c("ANOTHER", "COMMON", "ZEBRA")
)

我想将这个数据框与这个数据框连接起来:

selection <- tibble(
  x_prefix = c("A", "B", "C"),
  type = c("One type", "Other type", "Other type")
)

我想用

x
x_prefix
列进行 INNER JOIN,其想法是,如果
x_prefix
x
的前缀,则保留一行。

预期的答案是:

answer <- tibble(
  x = c("ANOTHER", "COMMON"),
  type = c("One type", "Other type")
)

如何使用 dplyr 做到这一点?

r dplyr tidyverse
2个回答
1
投票

您可以使用

fuuzy_inner_join
作为匹配函数来执行
str_detect
。符号“^”来自正则表达式,意思是字符串的开头,因此我们需要将其
paste
添加到您的模式中,以仅匹配以
x_prefix
开头的字符串。

library(fuzzyjoin)
library(tidyverse)

fuzzy_inner_join(data, selection, by = c("x" = "x_prefix"), 
                 match_fun = \(x, y) str_detect(x, paste0("^", y))) |> 
  select(-x_prefix)

# A tibble: 2 x 2
  x       type      
  <chr>   <chr>     
1 ANOTHER One type  
2 COMMON  Other type

0
投票

显而易见的解决方案是创建一个临时

x_prefix
列并在其上进行内部联接

data %>%
  mutate(x_prefix = substr(x, 1, 1)) %>%
  inner_join(selection, by = "x_prefix") %>%
  select(-x_prefix)
#> # A tibble: 2 x 2
#>   x       type      
#>   <chr>   <chr>     
#> 1 ANOTHER One type  
#> 2 COMMON  Other type
© www.soinside.com 2019 - 2024. All rights reserved.