Why is one_of() called that?

MissMonicaE picture MissMonicaE · Aug 24, 2017 · Viewed 14.5k times · Source

Why is dplyr::one_of() called that? All the other select_helpers names make sense to me, so I'm wondering if there's an aspect of one_of() that I don't understand.

My understanding of one_of() is that it just lets you select variables using a character vector of their names instead of putting their names into the select() call, but then you get all of the variables whose names are in the vector, not just one of them. Is that wrong, and if it's correct, where does the name one_of() come from?

Answer

CPak picture CPak · Sep 16, 2017

one_of allows for guessing or subset-matching

Let's say I know in general my column names will come from c("mpg","cyl","garbage") but I don't know which columns will be present because of interactivity/reactivity

mtcars %>% select(one_of(c("mpg","cyl","garbage")))

evaluates but provides a message

Warning message:
Unknown variables: `garbage`

In contrast

mtcars %>% select(mpg, cyl, garbage)

does not evaluate and gives the error

Error in overscope_eval_next(overscope, expr) : 
  object 'garbage' not found