使用ggplot2进行元编程

4

我一直试图减少大量复制和粘贴所需的工作量,以创建具有稍微不同功能/数据片段的许多图表。

这是一个简化的示例:

test <- data.table(a=c("x","y"), b=seq(1,3), c=rnorm(18))

fixedSlices <- function(input, rowfacet, colfacet, metric){
  calc <- substitute(metric)
  bygroup<-c(rowfacet,colfacet)
  aggregates <- input[,eval(calc),by=bygroup]

  ggplot(aggregates) + geom_point(stat="identity") + aes(x="", y=V1) + facet_grid(a ~ b)
}
fixedSlices(test, "a", "b", mean(c)) #works

dynamicSlices <- function(input, rowfacet, colfacet, metric){
  calc <- substitute(metric)
  bygroup<-c(rowfacet,colfacet)
  aggregates <- input[,eval(calc),by=bygroup]

  ggplot(aggregates) + geom_point(stat="identity") + aes(x="", y=V1) + facet_grid(eval(rowfacet) ~ eval(colfacet))
}
dynamicSlices(test, "a", "b", mean(c))
#Error in layout_base(data, rows, drop = drop) : At least one layer must contain all variables used for facetting

我希望我的函数能够接受作为参数的分面变量。关于在数据表中按列进行分组,我已经成功实现了这一点,但无法在ggplot中进行分面。


这里应该使用 aes_string 而不是 aes,对吗? - marbel
2个回答

6

您应该使用

... + facet_grid(as.formula(sprintf("%s ~ %s", rowfacet, colfacet))

在你的代码中。


5

facet_grid()接受一个公式对象,你可以使用as.formula()将字符串转换为公式对象。 你可以像这样做:

 facet_grid(as.formula(paste(rowfacet, "~", colfacet)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接