查看源代码str_replace
。
function (string, pattern, replacement)
{
replacement <- fix_replacement(replacement)
switch(type(pattern), empty = , bound = stop("Not implemented",
call. = FALSE), fixed = stri_replace_first_fixed(string,
pattern, replacement, opts_fixed = attr(pattern, "options")),
coll = stri_replace_first_coll(string, pattern, replacement,
opts_collator = attr(pattern, "options")), regex = stri_replace_first_regex(string,
pattern, replacement, opts_regex = attr(pattern,
"options")), )
}
<environment: namespace:stringr>
这导致find fix_replacement
,它位于Github,我也将其放在下面。如果您在主环境中运行它,您会发现fix_replacement(NA)
返回NA
. 您可以看到它依赖于stri_replace_all_regex
,它来自stringi
包。
fix_replacement <- function(x) {
stri_replace_all_regex(
stri_replace_all_fixed(x, "$", "\\$"),
"(?<!\\\\)\\\\(\\d)",
"\\$$1")
}
有趣的是,当使用您的参数(您的、、和)运行时,两者都会stri_replace_first_fixed
返回stri_replace_first_regex
。问题在于,并且是 C++ 代码,所以要弄清楚发生了什么变得有点棘手。c(NA,NA,NA)
string
pattern
replacement
stri_replace_first_fixed
stri_replace_first_regex
stri_replace_first_fixed
可以在这里找到。
stri_replace_first_regex
可以在这里找到。
据我所知,在有限的时间和我相对生疏的 C++ 知识中,该stri__replace_allfirstlast_fixed
函数replacement
使用stri_prepare_arg_string
. 根据文档,如果遇到 NA,它将引发错误。除此之外,我没有时间完全追踪它,但我怀疑这个错误可能导致所有 NA 的奇怪返回。