gpt4 book ai didi

r - str_replace "NA"的异常行为

转载 作者:行者123 更新时间:2023-12-04 04:16:34 25 4
gpt4 key购买 nike

我正在尝试将字符串转换为数字,并且遇到了str_replace的某些意外行为。这是一个最小的工作示例:

library(stringr)
x <- c("0", "NULL", "0")

# This works, i.e. 0 NA 0
as.numeric(str_replace(x, "NULL", ""))

# This doesn't, i.e. NA NA NA
as.numeric(str_replace(x, "NULL", NA))

在我看来,第二个示例应该起作用,因为它仅应使用 NA(这是字符矢量中的有效值)替换矢量中的第二个条目。但事实并非如此:内部 str_replace将所有三个条目都转换为 NA

这里发生了什么?我浏览了 str_replacestri_replace_all的文档,但没有看到明显的解释。

编辑:为了明确起见,这与R 3.1.3,Windows 7上的 stringr_1.0.0stringi_1.0-1一起使用。

最佳答案

查看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>

这导致找到 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_fixedstri_replace_first_regexc(NA,NA,NA))运行参数时, stringpattern都返回 replacement。问题是 stri_replace_first_fixedstri_replace_first_regex是C++代码,因此弄清楚正在发生的事情变得有些棘手。
stri_replace_first_fixed可以找到 here
stri_replace_first_regex可以找到 here

据我能在有限的时间和相对生锈的C++知识中辨别出的那样,函数 stri__replace_allfirstlast_fixed使用 replacement检查 stri_prepare_arg_string参数。根据 documentation的说明,如果遇到NA,它将引发错误。我没有时间完全跟踪它,但是我怀疑此错误可能导致所有NA的奇数返回。

关于r - str_replace "NA"的异常行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337873/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com