I'm trying to use dplyr to filter based on a dynamic variable.
I've figured out that to get filter to work, I need to enclose the variable name in parentheses. However, if I program this into a fuction, it does not work properly.
df_ex <- data.frame(a = 1:10, b = 11:20)
param <- quo(a)
# returns df_ex with column a, only, as expected
df_ex %>%
dplyr::select(!!param)
# returns expected df
df_ex %>%
dplyr::filter((!!param)==5)
# Now for the function
testfun <- function(test_df, filt_var){
filt_var_mod <- quo(filt_var)
test_df %>%
dplyr::filter((!!filt_var_mod)==5)
}
# returns empty df, not as expected
testfun(df_ex, "a")
I would like to learn to find the answers to these questions types of questions about dplyr for myself, so please feel free to refer me to the relevant part of the programming vignette