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,919
  • 4
  • 58
  • 71
Jacob H
  • 4,317
  • 2
  • 32
  • 39

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
  • 97,041
  • 11
  • 181
  • 245
2

You can also use:

d %>% select(one_of(v))
mtoto
  • 23,919
  • 4
  • 58
  • 71