R mutate - 与通配符匹配

R mutate - match with wild card

我正在尝试根据从单独的数据帧 df2.

中提取值的匹配函数,在数据帧 df1 中插入一列

df1:

var_field
abc
def
abc1
2def

df2:

setting_name setting_type
abc                   xyz
def                   mno

下面的代码设法做到这一点:

df1 <- df1 %>%
  mutate(match_col = df2[["setting_type"]][match(df1[["var_field"]], df2[["setting_name"]])])

我想为这个匹配添加通配符功能,这样即使在 var_field 中没有完全相同的匹配,它也可以从 df2 跨越 setting_type

带通配符的预期结果:

var_field  setting_type
abc                 xyz
def                 mno
abc1                xyz
2def                mno

我试过在上面的代码中使用 globrx 函数:

df1 <- df1 %>%
  mutate(match_col = df2[["setting_type"]][match(df1[["var_field"]], df2[[glob2rx(paste("*",setting_name,"*"))]])])

但是returns一个错误:

x Must extract column with a single valid subscript.
x Subscript `glob2rx(paste("*", df2$setting_name, "*"))` has size 18 but must be size 1.

我也尝试在 df2 中添加 glob2rx(paste("*", df2$setting_name, "*")) 作为额外的列,并使用它而不是 "setting_name" 进行匹配,但这也不起作用。

如有任何帮助,我们将不胜感激。

如果您想连接精确的子字符串,则不需要 fuzzyjoin

library(tidyverse)
df1 <- tribble(
  ~var_field,
  "abc",
  "def",
  "abc",
  "2def"
)
df2 <- tribble(
  ~setting_name, ~setting_type,
  "abc", "xyz",
  "def", "mno"
)

df1 %>%
  mutate(setting_name = var_field %>% str_extract(df2$setting_name)) %>%
  left_join(df2) %>%
  select(-setting_name)
#> Joining, by = "setting_name"
#> # A tibble: 4 x 2
#>   var_field setting_type
#>   <chr>     <chr>       
#> 1 abc       xyz         
#> 2 def       mno         
#> 3 abc       xyz         
#> 4 2def      mno