Skip to content

Commit ec51727

Browse files
committed
Have str_subset() drop NAs from string.
The "missings never match" example from ?str_subset broke in commit d681e45, which added name preservation. The current commit keeps names while not matching NAs in string. Also added a test for missings never to match. > # stringr 1.5.2 > stringr::str_subset(c("a", NA, "b"), ".") [1] "a" "b" > # pak::pkg_install("tidyverse/stringr@d681e45") > stringr::str_subset(c("a", NA, "b"), ".") [1] "a" NA "b" > stringr::str_subset(c(First = "a", Second = NA, Third = "b"), ".") First <NA> Third "a" NA "b" > # Current version > stringr::str_subset(c(First = "a", Second = NA, Third = "b"), ".") First Third "a" "b"
1 parent 195159c commit ec51727

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

R/subset.R

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,13 +30,18 @@ str_subset <- function(string, pattern, negate = FALSE) {
3030
check_lengths(string, pattern)
3131
check_bool(negate)
3232

33-
switch(type(pattern),
34-
empty = no_empty(),
35-
bound = no_boundary(),
36-
fixed = string[str_detect(string, pattern, negate = negate)],
37-
coll = string[str_detect(string, pattern, negate = negate)],
38-
regex = string[str_detect(string, pattern, negate = negate)])
33+
if (type(pattern) == "empty") no_empty()
34+
if (type(pattern) == "bound") no_boundary()
3935

36+
idx <- str_detect(string, pattern, negate = negate)
37+
# str_detect() returns NA for NAs in string, but str_subset() should drop them
38+
idx[is.na(idx)] <- FALSE
39+
out <- string[idx]
40+
# Work around the fact that as.character() drops names
41+
nm <- names(out)
42+
out <- as.character(out)
43+
names(out) <- nm
44+
out
4045
}
4146

4247
#' Find matching indices

tests/testthat/test-subset.R

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,3 +52,8 @@ test_that("str_subset() preserves names of retained elements", {
5252
out <- str_subset(x, "[12]")
5353
expect_equal(names(out), c("B", "A"))
5454
})
55+
56+
test_that("str_subset() never matches missing values", {
57+
expect_equal(str_subset(c("a", NA, "b"), "."), c("a", "b"))
58+
expect_identical(str_subset(NA, "."), character(0))
59+
})

0 commit comments

Comments
 (0)