我正在尝试以编程方式使用 dplyr:带引号变量的过滤器行为是不可理解的。
经过几次尝试分析真实数据后,我创建了以下虚拟数据。
dt <- data.frame(
sex = rep(c("F","M"), 50),
height = runif(100, 1, 1000),
weight = rep(c(2, 100), 50),
value = runif(100, 1, 1000 ),
stringsAsFactors = FALSE
)
library(dplyr)
wizard_fun_1 <- function(param1){
par1 <- enquo(param1)
dt %>% select(height, !!par1)
}
wizard_fun_1("sex")
# as expected
#1 74.875344 F
#2 846.614856 M
#.....
wizard_fun_2 <- function(param1){
par1 <- enquo(param1)
dt %>% select(height, !!par1) %>%
filter( (!!par1) == 'M')
}
wizard_fun_2('sex')
#[1] height sex
# ... zero rows....
怎么了?提前感谢您的任何想法!