I'm writing a function where I supply a variable name as a symbol. At a different step in the function, I want to use the variable name as a string. Per the documentation, rlang::as_string
"converts symbols to character strings."
Here is a basic example. This function returns a tibble with a column titled mean
.
find_mean <- function(varname){
tibble(mean = mean(pull(mtcars, {{varname}})))
> find_mean(qsec)
# A tibble: 1 × 1
mean
<dbl>
1 17.8
I want to add another column with the variable name as a string, like so:
# A tibble: 1 × 2
mean variable
<dbl> <chr>
1 17.8 qsec
I thought this would work.
find_mean <- function(varname){
tibble(mean = mean(pull(mtcars, {{varname}})),
variable = rlang::as_string({{varname}}))
}
But it returns this error.
> find_mean(qsec)
Error in ~qsec : object 'qsec' not found
I know I'm making some basic error regarding rlang
's nonstandard evaluation rules, but googling around hasn't helped me figure this out yet.
ensym
- that's what I was missing! This also worked in my more complicated real use-case. Thanks a lot @akrun. Not the first time you've saved me great frustration. – Allodium