10

Often I'll want to select a subset of variables where the subset is the result of a function. In this simple case, I first get all the variable names which pertain to width characteristics

library(dplyr)
library(magrittr)

data(iris)

width.vars <- iris %>% 
                names %>% 
                extract(grep(".Width", .))

Which returns:

>width.vars
 [1] "Sepal.Width" "Petal.Width"

It would be useful to be able to use these returns as a way to select columns (and while I'm aware that contains() and its siblings exist, there are plenty of more complicated subsets I would like to perform, and this example is made trivial for the purpose of this example.

If I was to attempt to use this function as a way to select columns, the following happens:

iris %>% 
  select(Species,
         width.vars)

Error: All select() inputs must resolve to integer column positions.
The following do not:
*  width.vars

How can I use dplyr::select with a vector of variable names stored as strings?

tomw
  • 3,114
  • 4
  • 29
  • 51

2 Answers2

20

Within dplyr, most commands have an alternate version that ends with a '_' that accept strings as input; in this case, select_. These are typically what you have to use when you are utilizing dplyr programmatically.

iris %>% select_(.dots=c("Species",width.vars))
Craig
  • 4,492
  • 2
  • 19
  • 22
7

First of all, you can do the selection in dplyr with

iris %>% select(Species, contains(".Width"))

No need to create the vector of names separately. But if you did have a list of columns as string names, you could do

width.vars <- c("Sepal.Width", "Petal.Width")
iris %>% select(Species, one_of(width.vars))

See the ?select help page for all the available options.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    thanks for your answer, but as I said in the question, I'm aware of `select`, and I'm interested in those cases where I wanted to do a more complicated function to a set of variable names. – tomw Oct 22 '15 at 15:47
  • 2
    So that's what `one_of` would do as shown above as well. – MrFlick Oct 22 '15 at 15:48