I am trying to use dplyr in the programming way: filter behavior with quoted variables are not understandable.
After several attempts to analyze the real data I had created a following dummy data.
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....
What's going wrong? Thank's in advanced for any ideas!
If you are using
enquo
, you should be calling your function without quotes. For examplewill work just fine. The
select
function can take strings or symbols. That is both of these will workBut that's not the same for
filter()
So be careful when jumping between strings and unquoted symbols/names. When you are using quote stings, you're not using non-standard evaluation at all really.