Writing ggplot functions in R with optional arguments

前端 未结 3 2004
故里飘歌
故里飘歌 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:21

    the way to set up a default is like this:

    testFunction <- function( requiredParam, optionalParam=TRUE, alsoOptional=123 ) {
      print(requiredParam)
      if (optionalParam==TRUE) print("you kept the default for optionalParam")
      paste("for alsoOptional you entered", alsoOptional)
    }
    

    *EDIT*

    Oh, ok... so I think I have a better idea of what you are asking. It looks like you're not sure how to bring the optional facet into the ggplot object. How about this:

      qhist <- function(variable, df, heading, facets=NULL) {
      d <- qplot(variable, data = df, geom = "histogram", binwidth = 2000, 
            xlab = "Salary", ylab = "Noms") + 
      theme_bw() +
      scale_x_continuous(limits=c(40000,250000), 
                 breaks=c(50000,100000,150000,200000,250000), 
                 labels=c("50k","100k","150k","200k","250k")) +
      opts(title = heading, plot.title = theme_text(face = "bold", 
           size = 14), strip.text.x = theme_text(size = 10, face = 'bold')) 
      # If facets argument supplied add the following, else do not add this code
      if (is.null(facets)==FALSE) d <- d + facet_wrap(as.formula(paste("~", facets)))
      d
      return(d)
      }
    

    I have not tested this code at all. But the general idea is that the facet_wrap expects a formula, so if the facets are passed as a character string you can build a formula with as.formula() and then add it to the plot object.

    If I were doing it, I would have the function accept an optional facet formula and then pass that facet formula directly into the facet_wrap. That would negate the need for the as.formula() call to convert the text into a formula.

提交回复
热议问题