Writing ggplot functions in R with optional arguments

前端 未结 3 2005
故里飘歌
故里飘歌 2021-02-06 09:26

I have a series of ggplot graphs that I\'m repeating with a few small variations. I would like to wrap these qplots with their options into a function to avoid a lot of repetiti

3条回答
  •  感情败类
    2021-02-06 10:17

    Probably, the best way is to stop using such unusual variable names including commas or spaces.

    As a workaround, here is an extension of @JDLong's answer. The trick is to rename the facet variable.

    f <- function(dat, facet = NULL) {
        if(!missing(facet)) {
            names(dat)[which(names(dat) == facet)] <- ".facet."
            ff <- facet_wrap(~.facet.)
        } else {
            ff <- list()
        }
        qplot(x, y, data = dat) + ff
    }
    
    d <- data.frame(x = 1:10, y = 1:10, "o,o" = gl(2,5), check.names=F)
    
    f(d, "o,o")
    f(d)
    

提交回复
热议问题