【发布时间】:2017-09-11 19:03:51
【问题描述】:
我正在尝试以编程方式使用 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....
怎么了? 提前感谢您的任何想法!
【问题讨论】:
-
请参阅here,了解如何使用字符串作为输入。
标签: r dplyr non-standard-evaluation