Skip to content

Commit

Permalink
str_subset to keep names if present (#560)
Browse files Browse the repository at this point in the history
closes #507
  • Loading branch information
edward-burn authored Aug 15, 2024
1 parent 8816213 commit d681e45
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
12 changes: 6 additions & 6 deletions R/subset.R
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ str_subset <- function(string, pattern, negate = FALSE) {
check_bool(negate)

switch(type(pattern),
empty = no_empty(),
bound = no_boundary(),
fixed = stri_subset_fixed(string, pattern, omit_na = TRUE, negate = negate, opts_fixed = opts(pattern)),
coll = stri_subset_coll(string, pattern, omit_na = TRUE, negate = negate, opts_collator = opts(pattern)),
regex = stri_subset_regex(string, pattern, omit_na = TRUE, negate = negate, opts_regex = opts(pattern))
)
empty = no_empty(),
bound = no_boundary(),
fixed = string[str_detect(string, pattern, negate = negate)],
coll = string[str_detect(string, pattern, negate = negate)],
regex = string[str_detect(string, pattern, negate = negate)])

}

#' Find matching indices
Expand Down
7 changes: 7 additions & 0 deletions tests/testthat/test-subset.R
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,10 @@ test_that("can't use boundaries", {
str_subset(c("a", "b c"), boundary())
})
})

test_that("keep names", {
fruit <- c(A = "apple", B = "banana", C = "pear", D = "pineapple")
expect_identical(names(str_subset(fruit, "b")), "B")
expect_identical(names(str_subset(fruit, "p")), c("A", "C", "D"))
expect_identical(names(str_subset(fruit, "x")), as.character())
})

0 comments on commit d681e45

Please sign in to comment.