Writing ggplot functions in R with optional arguments

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

    Note that you can also use missing(facets) to check if the facets argument was specified or not. If you use @JD Long's solution, it would look something like this:

    qhist <- function(variable, df, heading, facets) {
      ... insert @JD Longs' solution ...
    
      if (!missing(facets)) d <- d + facet_wrap(as.formula(paste("~", facets)))
      return(d)
    }
    

    ...Note that I also changed the default argument from facets=NULL to just facets.

    Many R functions use missing arguments like this, but in general I tend to prefer @JD Long's variant of using a default argument value (like NULL or NA) when possible. But sometimes there is no good default value...

提交回复
热议问题