我经常发现编写使用数据集的不同子集创建绘图的函数很有用。例如,获取如下数据:
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))
我想要一个函数来为我指定的 con1:4 变量的任何组合创建一个分面图。我想要的简化版本如下所示:
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)
这适用于传递单个变量,但不适用于我想绘制交互。例如,将 groupVar 设置为 'con1*con2' 不会产生所需的结果 - 即我手动指定的图
facet_wrap(~con1*con2)
我明白(毫无疑问在相当肤浅的层面上)为什么这不起作用,但无法找出解决方案。我的解决方法是为每次交互创建新变量,以便我可以将交互作为单个变量传递给 facet_wrap - 例如对于 con1*con2 交互:
dat <- dat %>%
mutate(con1_con2 = paste(con1, con2, sep = '_'))
groupVar <- 'con1_con2'
plotFunction(groupVar = groupVar)
给出了想要的结果。
对于如何通过 groupVar 变量(或其他一些方法)将交互传递给函数以便无需创建新变量的任何建议,我将不胜感激。
最佳答案
您可以使用字符向量参数语法代替 ~
公式语法( 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)
只要记得更新
ggtitle
粘贴命令也是如此。
关于r - 使用 dplyr/ggplot 将变量之间的交互传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615677/