s_match()
is a simpler version of matches()
in <tidy-select
>.
It is designed to select columns in a Stata-like style.
As matches()
, s_match()
must be used
within a selecting function, such as
ds()
or
dplyr::across()
.
Arguments
- string
A character vector of column names like selecting a varlist in Stata
keep
command.- ignore.case
If
TRUE
, the default, ignores case when matching names.- vars
A character vector of variable names. If not supplied, the variables are taken from the current selection context (as established by functions like
select()
orpivot_longer()
).
Details
*
matches zero or more characters.~
matches one or more characters.?
matches one character.[a-h]
matches any character in the range froma
toh
.[1-12]
matches any number in the range from1
to12
.var1-var5
is NOT used to select a range of variables. Usevar1:var5
out ofs_match()
instead.
Examples
tb <- paste0("x", 1:15) %>%
tibble::as_tibble() %>%
tidyr::pivot_wider(names_from = value)
tb
#> # A tibble: 1 × 15
#> x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13
#> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
#> 1 x1 x2 x3 x4 x5 x6 x7 x8 x9 x10 x11 x12 x13
#> # ℹ 2 more variables: x14 <chr>, x15 <chr>
# List variable names by ds()
ds(tb)
#> [1] "x1" "x2" "x3" "x4" "x5" "x6" "x7" "x8" "x9" "x10" "x11" "x12"
#> [13] "x13" "x14" "x15"
tb %>%
ds(s_match("x1*"))
#> [1] "x1" "x10" "x11" "x12" "x13" "x14" "x15"
tb %>%
ds(s_match("x1~"))
#> [1] "x10" "x11" "x12" "x13" "x14" "x15"
tb %>%
ds(s_match("*5"))
#> [1] "x5" "x15"
tb %>%
ds(s_match("?5"))
#> [1] "x5"
tb %>%
ds(s_match("x[9-15]"))
#> [1] "x9" "x10" "x11" "x12" "x13" "x14" "x15"
if (FALSE) {
tb %>%
ds(s_match("x1-x5"))
}
tb %>%
ds(x1:x5)
#> [1] "x1" "x2" "x3" "x4" "x5"