2015-12-17 7 views
9

文字列を数値に変換しようとしていて、予期しない動作が発生しました。str_replace。ここでは最小の作業例を示しますstr_replace "NA"での予期しない動作

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とベクトルの2番目のエントリを置き換える必要がありますように、2番目の例では、動作するはずです。しかし、そうではありません:内部str_replaceは、すべての3つのエントリをNAに変換します。

ここでは何が起こっていますか?私はstr_replacestri_replace_allのドキュメントを見てきましたが、明らかな説明はありません。

EDIT:明確にするために、これはR 3.1.3にstringr_1.0.0stringi_1.0-1であり、Windows 7の

+1

確かに修正が必要なソースコードで予期しない動作、あなたはNAにそれを操作できるようにする文字列を提供する必要があります: 'as.numeric(str_replace( x、 "NULL"、 "NA")) ' –

+0

回避策はありますか? 'x < - c(" 0 "、" NULL "、" 0 "); y < - x; y [y == "NULL"] < - NA; (1)0 NA 0' – bubble

+1

私は何かが欠けているに違いありません。 'base'関数をラップします。今は 'stringi'関数をラップします。あなたは私が推測する 'stringr'の古いバージョンを持っています。 'gsub'はここで正しく動作します。 –

答えて

3

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") 
} 

興味深いのは、あなたのパラメータ(あなたstringpattern、およびreplacement)を実行したときstri_replace_first_fixedstri_replace_first_regex両方がc(NA,NA,NA)を返すということです。問題はstri_replace_first_fixedstri_replace_first_regexがC++コードなので、何が起こっているのか把握するのが少し難解です。

stri_replace_first_fixedは、hereである。

stri_replace_first_regexhereを見つけることができる。

限られた時間と私の比較的錆びたC++の知識で分かる限り、stri__replace_allfirstlast_fixed関数はstri_prepare_arg_stringを使用してreplacement引数をチェックします。そのためにdocumentationによれば、NAに遭遇するとエラーになります。私はこれを超えて完全に追跡する時間はありませんが、このエラーがすべてのNAの奇妙な復帰を引き起こしていると思われます。

3

これはstringiパッケージにバグがあったが、今ではfixedstringrstringiに基づいていることをリコール - 前者はあまり影響を受けされなければならない)です。我々が得る最新の開発版では

stri_replace_all_fixed(c("1", "NULL"), "NULL", NA) 
## [1] "1" NA 
+0

stringi_1を呼び出すstringr1_2_0 1.5?問題はgithubで閉じられていたのを見ても、https://github.com/tidyverse/stringr/issues/110どのようなアイデアが何をしているのですか?ありがとう! – Matifou

関連する問題