我一直试图减少大量复制和粘贴所需的工作量,以创建具有稍微不同功能/数据片段的许多图表。
这是一个简化的示例:
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中进行分面。