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?
Note: one_of is a helper function, it basically suggest that you take elements from a character vector. Note: contains() is another helper function, it suggests that whatever inside the function is a literal string. In other words it needs to match a name exactly.
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
The way I think about it is that select()
eventually evaluates to a logical vector. So if you use starts_with
it goes through the variables in the dataframe and asks whether the variable name starts with the right set of characters. one_of
does the same thing but asks whether the variable name is one of the names listed in the character vector. But as they say, naming things is hard!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With