I would like to return an object vector (e.g. a list of variables) as a character vector in R. This is as close as I've gotten:
library(tidyverse)
data <- as_tibble(mtcars)
foo <- function (vars) {
as.character(enexpr(vars))
}
foo(c(hp, drat, wt))
I would like this to return [1] "hp" "drat" "wt"
but instead I'm getting [1] "c" "hp" "drat" "wt"
.
The code below works but it seems inelegant (and requires reading in the data):
foo <- function (vars) {
names(select(data, {{ vars }}))
}
foo(c(hp, drat, wt))
The application is passing a selection of variables to a paste function so that they can be combined to make a formula.
Edit: It goes without saying, this would also obviously work:
foo <- function (vars) {
as.character(enexpr(vars))[-1]
}
foo(c(hp, drat, wt))
My feeling though is that there still must be a tidier (pun intended) way of doing this.
CodePudding user response:
How about something like this:
library(rlang)
foo <- function(...){
l <- quos(...)
sapply(l, quo_name)
}
foo(hp, drat, wt)
#>
#> "hp" "drat" "wt"
Created on 2022-07-06 by the reprex package (v2.0.1)
CodePudding user response:
I recommend tidyselect for this sort of things.
foo <- function (data, vars) {
tidyselect::eval_select(enquo(vars), data)
}
foo(mtcars, c(hp, drat, wt))
#> hp drat wt
#> 4 5 6
As a bonus you gain all of the tidyselect features:
foo(mtcars, starts_with("d"))
#> disp drat
#> 3 5
Note that you have to supply a data frame. This follows the tidyverse principle that unquoted object names can only refer to existing objects.