These functions allow you to select variables based on their names.

  • starts_with(): Starts with a prefix.

  • ends_with(): Ends with a suffix.

  • contains(): Contains a literal string.

  • matches(): Matches a regular expression.

  • num_range(): Matches a numerical range like x01, x02, x03.

  • one_of(): Matches variable names in a character vector.

  • everything(): Matches all variables.

  • last_col(): Select last variable, possibly with an offset.

starts_with(match, ignore.case = TRUE, vars = peek_vars())

ends_with(match, ignore.case = TRUE, vars = peek_vars())

contains(match, ignore.case = TRUE, vars = peek_vars())

matches(match, ignore.case = TRUE, perl = FALSE, vars = peek_vars())

num_range(prefix, range, width = NULL, vars = peek_vars())

one_of(..., .vars = peek_vars())

everything(vars = peek_vars())

last_col(offset = 0L, vars = peek_vars())

Arguments

match

A string.

ignore.case

If TRUE, the default, ignores case when matching names.

vars, .vars

A character vector of variable names. When called from inside selecting functions like dplyr::select() these are automatically set to the names of the table.

perl

Should Perl-compatible regexps be used?

prefix

A prefix that starts the numeric range.

range

A sequence of integers, like 1:5.

width

Optionally, the "width" of the numeric range. For example, a range of 2 gives "01", a range of three "001", etc.

...

One or more character vectors.

offset

Set it to n to select the nth var from the end.

Value

An integer vector giving the position of the matched variables.

Details

The order of selected columns is determined by the inputs.

Examples

nms <- names(iris) vars_select(nms, starts_with("Petal"))
#> Petal.Length Petal.Width #> "Petal.Length" "Petal.Width"
vars_select(nms, ends_with("Width"))
#> Sepal.Width Petal.Width #> "Sepal.Width" "Petal.Width"
vars_select(nms, contains("etal"))
#> Petal.Length Petal.Width #> "Petal.Length" "Petal.Width"
vars_select(nms, matches(".t."))
#> Sepal.Length Sepal.Width Petal.Length Petal.Width #> "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width"
vars_select(nms, Petal.Length, Petal.Width)
#> Petal.Length Petal.Width #> "Petal.Length" "Petal.Width"
vars_select(nms, everything())
#> Sepal.Length Sepal.Width Petal.Length Petal.Width Species #> "Sepal.Length" "Sepal.Width" "Petal.Length" "Petal.Width" "Species"
vars_select(nms, last_col())
#> Species #> "Species"
vars_select(nms, last_col(offset = 2))
#> Petal.Length #> "Petal.Length"
vars <- c("Petal.Length", "Petal.Width") vars_select(nms, one_of(vars))
#> Petal.Length Petal.Width #> "Petal.Length" "Petal.Width"
# The order of selected columns is determined from the inputs vars_select(names(mtcars), starts_with("c"), starts_with("d"))
#> cyl carb disp drat #> "cyl" "carb" "disp" "drat"
vars_select(names(mtcars), one_of(c("carb", "mpg")))
#> carb mpg #> "carb" "mpg"