Unexpected behaviour with str_replace "NA"

Look at the source code of 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>

This leads to finding fix_replacement, which is at Github, and I've put it below too. If you run it in your main environment, you find out that fix_replacement(NA) returns NA. You can see that it relies on stri_replace_all_regex, which is from the stringi package.

fix_replacement <- function(x) {
    stri_replace_all_regex(
        stri_replace_all_fixed(x, "$", "\\$"),
        "(?<!\\\\)\\\\(\\d)",
        "\\$$1")
}

The interesting thing is that stri_replace_first_fixed and stri_replace_first_regex both return c(NA,NA,NA) when run with your parameters (your string, pattern, and replacement). The problem is that stri_replace_first_fixed and stri_replace_first_regex are C++ code, so it gets a little trickier to figure out what's happening.

stri_replace_first_fixed can be found here.

stri_replace_first_regex can be found here.

As far as I can discern with limited time and my relatively rusty C++ knowledge, the function stri__replace_allfirstlast_fixed checks the replacement argument using stri_prepare_arg_string. According to the documentation for that, it will throw an error if it encounters an NA. I don't have time to fully trace it beyond this, but I would suspect that this error may be causing the odd return of all NAs.


This was a bug in the stringi package but now it is fixed (recall that stringr is based on stringi - the former shall be affected too).

With the most recent development version we get:

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

Tags:

R

Stringr

Stringi