在多个候选中找到多个子串的最佳匹配

Tha*_*uys 5 substring r

我有以下示例数据:

targets <- c("der", "das")
candidates <- c("sdassder", "sderf", "fongs")
Run Code Online (Sandbox Code Playgroud)

期望输出:

我想找到sdassder作为输出,因为它包含最多的匹配项targets(作为子字符串)。

我试过的:

x <- sapply(targets, function(target) sapply(candidates, grep, pattern = target)) > 0
which.max(rowSums(x))
Run Code Online (Sandbox Code Playgroud)

目标:

如您所见,我发现了一些技术上产生结果的脏代码,但我认为这不是最佳实践。我希望这个问题适合这里,否则我将转向代码审查。

我尝试了 mapply、do.call、outer,但没有找到更好的代码。

编辑:

在看到当前答案后,自己添加另一个选项。

使用管道:

sapply(targets, grepl, candidates) %>% rowSums %>% which.max %>% candidates[.]
Run Code Online (Sandbox Code Playgroud)

r2e*_*ans 3

我想你可以稍微简化一下。

matches <- sapply(targets, grepl, candidates)
matches
#        der   das
# [1,]  TRUE  TRUE
# [2,]  TRUE FALSE
# [3,] FALSE FALSE
Run Code Online (Sandbox Code Playgroud)

并使用以下命令查找匹配数rowSums

rowSums(matches)
# [1] 2 1 0
candidates[ which.max(rowSums(matches)) ]
# [1] "sdassder"
Run Code Online (Sandbox Code Playgroud)

(请注意,最后一部分并没有真正告知关系。)

如果您想查看每个候选人的个人匹配,您始终可以手动应用名称,尽管这只是一个美观的事情,对工作本身的增加很少。

rownames(matches) <- candidates
matches
#            der   das
# sdassder  TRUE  TRUE
# sderf     TRUE FALSE
# fongs    FALSE FALSE
rowSums(matches)
# sdassder    sderf    fongs 
#        2        1        0 
which.max(rowSums(matches))
# sdassder 
#        1        <------ this "1" indicates the index within the rowSums vector
names(which.max(rowSums(matches)))
# [1] "sdassder"
Run Code Online (Sandbox Code Playgroud)