str_replace" NA"的意外行为

时间:2015-12-17 15:10:11

标签: r stringr stringi

我试图将字符串转换为数字,并遇到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一致。

4 个答案:

答案 0 :(得分: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>

这导致找到fix_replacementGithub,我也把它放在下面。如果您在主要环境中运行它,则会发现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_regex在使用您的参数运行时返回c(NA,NA,NA)stringpatternreplacement })。问题是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参数。根据{{​​3}},如果遇到NA则会抛出错误。我没有时间完全追踪它,但我怀疑这个错误可能导致所有NA的奇怪回归。

答案 1 :(得分:3)

这是stringi包中的错误,但现在是fixed(回想stringr基于stringi - 前者也会受到影响。< / p>

使用最新的开发版本:

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

答案 2 :(得分:0)

还有一种使用NA_character_来解决此问题的方法,如图here

对该问题的简短回答:

library(stringr)
x <- c("0", "NULL", "0")
y <- as.numeric(str_replace(x, "NULL", NA_character_))

产生:

> y
[1]  0 NA  0
> typeof(y)
[1] "double"

走得更远

library(dplyr)
library(stringr)
# create a dummy dataset
ex = starwars %>% select(name, hair_color, homeworld) %>% head(6)
print(ex)
# lets say you want to replace all "Tatooine" by NA
# this produce the expected output
ex %>% mutate(homeworld = str_replace_all(homeworld, pattern = "Tatooine", NA_character_))

# HOWEVER,
# From Hadley's comment: "str_replace() has to replace parts of a string and replacing part of a string with NA doesn't make sense."
# then be careful using this method, see the example below:
ex %>% mutate(hair_color = str_replace_all(hair_color, pattern = "brown", NA_character_))
# all air colors with "brown", including "blond, grey" (Owen Lars, line 6) are now NA

输出

> print(ex)
# A tibble: 10 x 3
   name               hair_color    homeworld
   <chr>              <chr>         <chr>    
 1 Luke Skywalker     blond         Tatooine 
 2 C-3PO              NA            Tatooine 
 3 R2-D2              NA            Naboo    
 4 Darth Vader        none          Tatooine 
 5 Leia Organa        brown         Alderaan 
 6 Owen Lars          brown, grey   Tatooine  

> ex %>% mutate(homeworld = str_replace_all(homeworld, pattern = "Tatooine", NA_character_))
# A tibble: 10 x 3
   name               hair_color    homeworld
   <chr>              <chr>         <chr>    
 1 Luke Skywalker     blond         NA       
 2 C-3PO              NA            NA       
 3 R2-D2              NA            Naboo    
 4 Darth Vader        none          NA       
 5 Leia Organa        brown         Alderaan 
 6 Owen Lars          brown, grey   NA         

 > ex %>% mutate(hair_color = str_replace_all(hair_color, pattern = "brown", NA_character_))
# A tibble: 10 x 3
   name               hair_color    homeworld
   <chr>              <chr>         <chr>    
 1 Luke Skywalker     blond         Tatooine 
 2 C-3PO              NA            Tatooine 
 3 R2-D2              NA            Naboo    
 4 Darth Vader        none          Tatooine 
 5 Leia Organa        NA            Alderaan 
 6 Owen Lars          NA            Tatooine 

答案 3 :(得分:0)

这是使用 dplyr 的 across 方法和 stringr 包的解决方案。

df <- data.frame(x=c("a","b","null","e"),
                 y=c("g","null","h","k"))  

df2 <- df %>% 
  mutate(across(everything(),str_replace,"null",NA_character_))