0

Imagine I have a dataset as follows

d <- data.frame(a = 1:10, b = letters[1:10], c = sample(10))

Imagine that I also have a character vector containing variable names

v <- c("a", "b")

Using dplyr I would like to use v to select variables a & b.

This will not work,

d %>%
  select(v)

This is because the dplyr packages uses non standard evaluation and expects actual variable names to be passed rather then characters.

mtoto
  • 23,013
  • 3
  • 54
  • 70
Jacob H
  • 3,917
  • 2
  • 29
  • 36

2 Answers2

3

For standard evaluation, you will want to use the functions with an underscore after their given name. In this case that is select_(). And we will also need to use the .dots argument to insert your vector into the call.

d %>% select_(.dots = v)

See help(select) and vignette("nse") for more.

Rich Scriven
  • 93,629
  • 10
  • 165
  • 233
2

You can also use:

d %>% select(one_of(v))
mtoto
  • 23,013
  • 3
  • 54
  • 70