简体   繁体   中英

Pass interactions between variables to a function using dplyr/ggplot

I often find it useful to write functions that create a plot using different subsets of a dataset. For example, take data like these:

id <- seq(1:640)
con1 <- rep(c('hi', 'lo'), each = 320, times = 1)
con2 <- rep(c('up', 'down'), each = 160, times = 2)
con3 <- rep(c('fork', 'knife'), each = 80, times = 4)
con4 <- rep(c('carrot', 'broccoli'), each = 40, times = 8)
likert <- sample(c(1:5), 640, replace = T)

dat <- as.data.frame(cbind(id, con1, con2, con3, con4, likert))

I would like to have a function that would create a facetted plot for any combination of the con1:4 variables that I specify. A simplified version of what I would like looks like this:

groupVar <- 'con1'

plotFunction <- function(groupVar) {

  plot <- ggplot(data = dat) +
    geom_bar(aes(x = factor(likert))) +
    facet_wrap(~eval(parse(text = groupVar))) +
    ggtitle(paste('Preferences grouped by ',groupVar)) + 
    theme_bw()

  return(plot)

}

plotFunction(groupVar = groupVar)

This works for passing single variables, but not when I want to plot an interaction. For example, setting groupVar to 'con1*con2' does not result in the desired result - ie, the plot I would get from manually specifying

facet_wrap(~con1*con2)

I understand (no doubt on a fairly superficial level) why this doesn't work, but haven't been able to figure out the solution. My workaround has been to create new variables for each interaction, so that I can then pass the interaction to facet_wrap as a single variable - eg for the con1*con2 interaction:

dat <- dat %>%
  mutate(con1_con2 = paste(con1, con2, sep = '_'))

groupVar <- 'con1_con2'

plotFunction(groupVar = groupVar) 

gives the desired result.

I would be grateful for any advice on how I can pass interactions to the function via the groupVar variable (or some other method) so that there is no need to create the new variables.

You can use the character vector argument syntax instead of the ~ formula syntax ( docs ):

groupVar <- c('con1','con2')

plotFunction <- function(groupVar) {

  plot <- ggplot(data = dat) +
    geom_bar(aes(x = factor(likert))) +
    facet_wrap(groupVar) +
    ggtitle(paste('Preferences grouped by ', paste0(groupVar, collapse="*"))) + 
    theme_bw()

  return(plot)

}

plotFunction(groupVar = groupVar)

在此输入图像描述

Just remember to update the ggtitle paste command as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM