From d681e457000cde9e504ee9bea0ce10f54687f811 Mon Sep 17 00:00:00 2001 From: edward-burn <9583964+edward-burn@users.noreply.github.com> Date: Thu, 15 Aug 2024 10:15:44 -0700 Subject: [PATCH] str_subset to keep names if present (#560) closes #507 --- R/subset.R | 12 ++++++------ tests/testthat/test-subset.R | 7 +++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/R/subset.R b/R/subset.R index d0735b25..0cde8324 100644 --- a/R/subset.R +++ b/R/subset.R @@ -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 diff --git a/tests/testthat/test-subset.R b/tests/testthat/test-subset.R index 80fb9da6..001d7c54 100644 --- a/tests/testthat/test-subset.R +++ b/tests/testthat/test-subset.R @@ -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()) +})