R 使用ggplot2进行元编程

R 使用ggplot2进行元编程,r,ggplot2,data.table,R,Ggplot2,Data.table,我一直在努力减少复制和粘贴大量图表所需的数量,这些图表的功能/数据片段略有不同 下面是一个我正在尝试做的简化示例: 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)

我一直在努力减少复制和粘贴大量图表所需的数量,这些图表的功能/数据片段略有不同

下面是一个我正在尝试做的简化示例:

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
test您应该使用

... + facet_grid(as.formula(sprintf("%s ~ %s", rowfacet, colfacet))
在您的代码中。

facet\u grid()
接受公式对象,您可以使用
as.formula()
从字符串创建公式对象。因此,您应该能够执行以下操作:

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

这里不应该使用aes_字符串而不是aes吗?