I am writing a custom function that is expected to work with both unquoted
and "quoted"
inputs. I can implement it using rlang
. But it doesn't seem to work when "quoted"
arguments are provided using colnames
.
Any ideas on how this can be resolved?
library(tidyverse)
# function
cor_foo <- function(data, x1, x2) {
x1 <- rlang::ensym(x1)
x2 <- rlang::ensym(x2)
df <- dplyr::select(data, {{x1}}, {{x2}})
cor(df %>% dplyr::pull({{x1}}), df %>% dplyr::pull({{x2}}))
}
# works
cor_foo(mtcars, wt, mpg)
#> [1] -0.8676594
# works
cor_foo(mtcars, "wt", "mpg")
#> [1] -0.8676594
# checking strings that will be passed to the function as arguments
colnames(mtcars)[1]
#> [1] "mpg"
colnames(mtcars)[6]
#> [1] "wt"
# doesn't work with these inputs
cor_foo(mtcars, colnames(mtcars)[6], colnames(mtcars)[1])
#> Error: Only strings can be converted to symbols
Created on 2019-11-12 by the reprex package (v0.3.0)