我正在尝试使用 tidy 评估,如dplyr 0.7.0
.
但是,在内部的函数调用期间,mutate()
我遇到了错误。似乎没有像我预期的那样评估变量。
library(dplyr)
library(tibble)
library(tidyr)
myCor <- function(col1, col2) {
col1 <- enquo(col1)
col2 <- enquo(col2)
mtcars %>%
rownames_to_column("vehicle") %>%
select(vehicle, !!col1, !!col2) %>%
mutate(correlation=cor(!!col1, !!col2))
}
myCor("mpg", "disp")
# Error in mutate_impl(.data, dots) :
# Evaluation error: 'x' must be numeric.
相反,我必须使用这种不整洁的 eval 语法来获得所需的输出。
myCor <- function(col1, col2) {
col1_tidy <- enquo(col1)
col2_tidy <- enquo(col2)
mtcars %>%
rownames_to_column("vehicle") %>%
select(vehicle, !!col1_tidy, !!col2_tidy) %>%
mutate(correlation=cor(eval(parse(text=col1)), eval(parse(text=col2))))
}
myCor("mpg", "disp")
# vehicle mpg disp correlation
# 1 Mazda RX4 21.0 160.0 -0.8475514
# 2 Mazda RX4 Wag 21.0 160.0 -0.8475514
# 3 Datsun 710 22.8 108.0 -0.8475514
# 4 Hornet 4 Drive 21.4 258.0 -0.8475514
# ...
有没有办法在这个例子中使用整洁的评估?