假设我有这些数据:
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 做到这一点?
您可以使用
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
显而易见的解决方案是创建一个临时
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