我正在编写一个自定义函数,预计可以同时使用unquoted
和"quoted"
输入。我可以使用rlang
. 但是当"quoted"
使用colnames
.
关于如何解决这个问题的任何想法?
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
由reprex 包(v0.3.0)于 2019 年 11 月 12 日创建