r - Is it possible to return a formula from a function? -
i'm lazy guy don't want type same codes again , again (not copy , paste :p). i'm wondering if it's possible write function return text strings as formula, next time, when want use pack of commends, can call function , whole piece of codes pasted in automatically.
for example, time, i'm using ggplot2
produce box plots , want customizations plot. have
ggplot(abc, aes(group, abcabc))+geom_boxplot(aes(fill=group)) + geom_hline(yintercept=0, color="grey") + theme(panel.background=element_rect(fill = "white")) + scale_fill_manual(values = c("white", "white"))
you can see last 2 lines of codes doing formatting setup. can use these 2 lines of codes every time when want generate boxplot in format in future. if can write function can return these 2 lines of codes formula, can use function sort of themes in ggplot
in future. tried write function this:
box.format<-function(){ return(as.formula('theme(panel.background=element_rect(fill = "white")) + scale_fill_manual(values = c("white", "white"))')) }
however, got message this:
error: don't know how add scale_fill_manual(values = c("white", "white")) theme object
does know how fix error or there other ways so?
i guess may try closure. below quick trial although not tested fully. ideally should able create own function factory closures.
mygg <- function(...) { function(data, x, y) { ggplot(data, aes(x, y))+geom_boxplot(aes(fill=x)) + geom_hline(yintercept=0, color=color_param) + theme(panel.background=element_rect(fill = back_param)) + scale_fill_manual(values = c(scale_param_x, scala_param_y)) } } gg <- mygg(color_param = "grey", back_param = "white", scale_param_x = "white", scale_param_y = "white") gg function(data, x, y) { ggplot(data, aes(x, y))+geom_boxplot(aes(fill=x)) + geom_hline(yintercept=0, color=color_param) + theme(panel.background=element_rect(fill = back_param)) + scale_fill_manual(values = c(scale_param_x, scala_param_y)) } <environment: 0x0000000018d7cea0>
Comments
Post a Comment