Skip to content

Commit 047df56

Browse files
committed
Implement str_which
Fixes #129
1 parent 34dc5ee commit 047df56

File tree

4 files changed

+33
-6
lines changed

4 files changed

+33
-6
lines changed

NAMESPACE

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ export(str_trim)
4040
export(str_trunc)
4141
export(str_view)
4242
export(str_view_all)
43+
export(str_which)
4344
export(str_wrap)
4445
export(word)
4546
import(stringi)

NEWS.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
vector. If `replacement` is `NA_character_` it replaces the complete string
1515
with replaces with `NA` (#124).
1616

17+
* New `str_which()` mimics `grep()` (#129).
18+
1719
* All functions that take a locale (e.g. `str_to_lower()` and `str_sort()`)
1820
default to "en" (English) to ensure that the default is consistent across
1921
platforms.

R/subset.R

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
#' Keep strings matching a pattern.
1+
#' Keep strings matching a pattern, or find positions.
2+
#'
3+
#' \code{str_subset()} is a wrapper around \code{x[str_detect(x, pattern)]},
4+
#' and is equivalent to \code{grep(pattern, x, value = TRUE)}.
5+
#' \code{str_which()} is a wrapper around \code{which(str_detect(x, pattern))},
6+
#' and is equivalent to \code{grep(pattern, x)}.
27
#'
3-
#' This is a convenient wrapper around \code{x[str_detect(x, pattern)]}.
48
#' Vectorised over \code{string} and \code{pattern}
59
#'
610
#' @inheritParams str_detect
@@ -11,13 +15,16 @@
1115
#' @examples
1216
#' fruit <- c("apple", "banana", "pear", "pinapple")
1317
#' str_subset(fruit, "a")
18+
#' str_which(fruit, "a")
19+
#'
1420
#' str_subset(fruit, "^a")
1521
#' str_subset(fruit, "a$")
1622
#' str_subset(fruit, "b")
1723
#' str_subset(fruit, "[aeiou]")
1824
#'
19-
#' # Missings are silently dropped
25+
#' # Missings never match
2026
#' str_subset(c("a", NA, "b"), ".")
27+
#' str_which(c("a", NA, "b"), ".")
2128
str_subset <- function(string, pattern) {
2229
switch(type(pattern),
2330
empty = ,
@@ -27,3 +34,9 @@ str_subset <- function(string, pattern) {
2734
regex = stri_subset_regex(string, pattern, omit_na = TRUE, opts_regex = opts(pattern))
2835
)
2936
}
37+
38+
#' @export
39+
#' @rdname str_subset
40+
str_which <- function(string, pattern) {
41+
which(str_detect(string, pattern))
42+
}

man/str_subset.Rd

Lines changed: 14 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)