有
Original Replace1 Replace2
timothy timoth timothys
我想在数据框中一起输出原始字符串和所有可能的结果,如下所示。
{{1}}
这可能还是有更好的功能使用?
答案 0 :(得分:1)
我个人将它保持为“长”格式而不是宽屏(你可以随后转发):
data.frame(
original = "timothy",
replacement = agrep('timothy', c('timo','tim','timoth', 'timothys'), max.distance = 0.01, value=TRUE),
stringsAsFactors=FALSE
)
## original replacement
## 1 timothy timoth
## 2 timothy timothys
你可能不止一次这样做,所以我会把它变成一个功能。而且,由于agrep()
的输出可能是character(0)
,我们需要处理它,所以我们也会添加辅助函数:
`%|l0%` <- function(x, y) if (length(x) == 0) y else x
agrep_to_data_frame <- function(pattern, x, max.distance=0.01, costs=NULL) {
data.frame(
original = pattern,
replacement = agrep(pattern, x, max.distance = max.distance, value=TRUE) %|l0% NA_character_,
stringsAsFactors=FALSE
)
}
而且,现在只需拨打一个电话即可在purrr::map2()
或mapply()
等处使用
agrep_to_data_frame('timothy', c('timo','tim','timoth', 'timothys'))
## original replacement
## 1 timothy timoth
## 2 timothy timothys