Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions r/R/dplyr-funcs-string.R
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,26 @@ register_bindings_string_regex <- function() {
if (length(replacement) != 1) {
validation_error("`replacement` must be a length 1 character vector")
}
# An NA replacement sets the whole string to NA wherever the pattern
# matches, matching base::sub()/gsub() and stringr::str_replace(). The
# replace_substring[_regex] kernels don't support this, so rewrite it as
# if_else(<pattern matches>, NA, x). GH-33432
if (is.na(replacement)) {
is_match <- Expression$create(
ifelse(fixed && !ignore.case, "match_substring", "match_substring_regex"),
x,
options = list(
pattern = format_string_pattern(pattern, ignore.case, fixed),
ignore_case = FALSE
)
)
return(Expression$create(
"if_else",
is_match,
Expression$scalar(NA_character_),
x
))
}
Expression$create(
ifelse(fixed && !ignore.case, "replace_substring", "replace_substring_regex"),
x,
Expand Down
27 changes: 27 additions & 0 deletions r/tests/testthat/test-dplyr-funcs-string.R
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,33 @@ test_that("sub and gsub with namespacing", {
)
})

test_that("str_replace/sub with an NA replacement match base/stringr (GH-33432)", {
df <- tibble(x = c("", "one", "two", "three", "four", NA))

# A match sets the whole value to NA; non-matches and NA input are unchanged
compare_dplyr_binding(
.input |>
transmute(
regex = str_replace(x, "o", NA_character_),
regex_all = str_replace_all(x, "o", NA_character_),
fixed = str_replace_all(x, fixed("o"), NA_character_),
ci = str_replace_all(x, regex("O", ignore_case = TRUE), NA_character_)
) |>
collect(),
df
)

compare_dplyr_binding(
.input |>
transmute(
subbed = sub("o", NA_character_, x),
gsubbed = gsub("o", NA_character_, x)
) |>
collect(),
df
)
})

test_that("str_replace and str_replace_all", {
x <- Expression$field_ref("x")

Expand Down
Loading