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.
as.numeric(str_replace(x, "NULL", "NA"))
– Franx <- c("0", "NULL", "0"); y <- x; y[y=="NULL"] <- NA; as.numeric(y)
– Raimentas.numeric(str_replace(x, "NULL", NA)) [1] 0 NA 0
– Emmalynnestringr
used to wrapbase
functions; now it wrapsstringi
functions. You have a old version ofstringr
I guess.gsub
behaves correctly here. – Stansburystringr
(stringr_1.0.0
) and it still works... – Vinniestringr 1.0.0
andstringi 1.0-1
(which appears to be the latest versions) and can reproduce OP's results. I'm on Ubuntu. OS dependent? – Stansburystringr 1.0.0
&stringi 1.0-1
and get the same as OP in a clean session (on OSX) – Lammastidestringr
andstringi
,R 3.2.1
on Windows 7 – Vinniestringr 1.0.0
,stringi 1.0-1
, andR 3.2.3
on Windows 7. I'm trying to trace the source now. – CavalierlyNA
is converted toNA_character_
, then it winds up here:x <- c("123", "NULL", "456"); stringi:::stri_replace_first_regex(x, "NULL", NA_character_)
. (I changed the numbers to remove any possible issues with 0). After that it descends into C code... – Shelving