I wrote a markdown report that uses hard-coded data and grouping variables. I'm trying to make it more flexible by using dynamic field names instead to avoid extensive find/replace editing when I process data with different headers.
Incorporating dynamic variable names in downstream functions has been challenging; I'm struggling to find a solution for functions bundled with the Multcomp package.
Would someone please demonstrate how to pass a dynamic field name into the glht function shown below?
Thank you.
#load library
library(multcomp)
#example data
my_data <- as.data.frame(HairEyeColor)
#setup group and data variables for use in other functions
group_var <- "Hair"
data_var <- "Freq"
#downstream ANOVA functions
anova <- aov(Freq ~ Hair, data = my_data) #hard-coded version works
anova <- rlang::eval_tidy(rlang::expr(aov(!!as.symbol(data_var) ~ !!as.symbol(group_var), data = my_data)))
#group_var works with helper functions
tukey <- glht(anova, linfct = mcp(Hair = "Tukey")) #hard-coded group works
tukey <- glht(anova, linfct = mcp(group_var = "Tukey")) #dynamic group_var doesn't work
tukey <- rlang::eval_tidy(rlang::expr(glht(anova, linfct = mcp(!!as.symbol(group_var) = "Tukey"))) #group_var doesn't work here, either