Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is one_of() called that?

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?

like image 464
MissMonicaE Avatar asked Aug 24 '17 15:08

MissMonicaE


People also ask

What does One_of () do in R?

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.


2 Answers

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     
like image 74
CPak Avatar answered Sep 21 '22 23:09

CPak


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!

like image 32
Shorpy Avatar answered Sep 18 '22 23:09

Shorpy