は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>
これはGithubである、fix_replacement
を見つけることにつながる、と私はあまりにも以下にそれを入れています。あなたの主な環境でそれを実行すると、fix_replacement(NA)
がNA
を返すことが分かります。 stringi
パッケージのstri_replace_all_regex
に依存していることがわかります。
fix_replacement <- function(x) {
stri_replace_all_regex(
stri_replace_all_fixed(x, "$", "\\$"),
"(?<!\\\\)\\\\(\\d)",
"\\$$1")
}
興味深いのは、あなたのパラメータ(あなたstring
、pattern
、およびreplacement
)を実行したときstri_replace_first_fixed
とstri_replace_first_regex
両方がc(NA,NA,NA)
を返すということです。問題はstri_replace_first_fixed
とstri_replace_first_regex
がC++コードなので、何が起こっているのか把握するのが少し難解です。
stri_replace_first_fixed
は、hereである。
stri_replace_first_regex
hereを見つけることができる。
限られた時間と私の比較的錆びたC++の知識で分かる限り、stri__replace_allfirstlast_fixed
関数はstri_prepare_arg_string
を使用してreplacement
引数をチェックします。そのためにdocumentationによれば、NAに遭遇するとエラーになります。私はこれを超えて完全に追跡する時間はありませんが、このエラーがすべてのNAの奇妙な復帰を引き起こしていると思われます。
確かに修正が必要なソースコードで予期しない動作、あなたはNAにそれを操作できるようにする文字列を提供する必要があります: 'as.numeric(str_replace( x、 "NULL"、 "NA")) ' –
回避策はありますか? 'x < - c(" 0 "、" NULL "、" 0 "); y < - x; y [y == "NULL"] < - NA; (1)0 NA 0' – bubble
私は何かが欠けているに違いありません。 'base'関数をラップします。今は 'stringi'関数をラップします。あなたは私が推測する 'stringr'の古いバージョンを持っています。 'gsub'はここで正しく動作します。 –