我正在做一些模糊文本匹配来匹配学校名称。这是我的数据示例,它是一个小标题中的两列:
data <- tibble(school1 = c("abilene christian", "abilene christian", "abilene christian", "abilene christian"),
school2 = c("a t still university of health sciences", "abilene christian university", "abraham baldwin agricultural college", "academy for five element acupuncture"))
data
# A tibble: 4 x 2
school1 school2
<chr> <chr>
1 abilene christian a t still university of health sciences
2 abilene christian abilene christian university
3 abilene christian abraham baldwin agricultural college
4 abilene christian academy for five element acupuncture
我想做的是使用stringdist
遍历所有可用methods
并返回一个看起来像这样的表,除了每个方法的列和返回的值之外,我的原始文本仍然存在:
# A tibble: 4 x 12
school1 school2 osa lv dl hamming lcs qgram cosine jaccard jw soundex
<chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 abilene christian a t still … 29.0 29.0 29.0 Inf 36.0 24.0 0.189 0.353 0.442 1.00
2 abilene christian abilene ch… 11.0 11.0 11.0 Inf 11.0 11.0 0.0456 0.200 0.131 0
3 abilene christian abraham ba… 28.0 28.0 28.0 Inf 35.0 25.0 0.274 0.389 0.431 1.00
4 abilene christian academy fo… 28.0 28.0 28.0 Inf 37.0 29.0 0.333 0.550 0.445 1.00
我可以使用以下方法使用 for 循环使其工作:
method_list <- c("osa", "lv", "dl", "hamming", "lcs", "qgram", "cosine", "jaccard", "jw", "soundex")
for (i in method_list) {
data[, i] <- stringdist(data$school1, data$school2, method = i)
}
我想做的是将其转换为更具可读性的 dplyr 语法,但我无法让循环与 mutate 一起使用。这是我所拥有的:
for (i in method_list) {
ft_result <- data %>%
mutate(i = stringdist(school1, school2, method = i))
}
运行此命令会返回 1 个附加列添加到我的原始数据中,称为“i”,每行的值为 1。
问题 1:for 循环是完成我想要达到的目标的最佳方式吗?我查看了 purrr 以查看是否可以使用 map 或 invoke 之类的东西,但我认为这些函数中的任何一个都不能满足我的要求。
问题 2:如果要使用 for 循环,我怎样才能使其与 mutate 一起使用?我尝试使用 mutate_at,但这也不起作用。