使用可选参数在R中编写ggplot函数

Tom*_*hon 7 r ggplot2

我有一系列的ggplot图表,我正在重复一些小的变化.我想将这些qplots的选项包装成一个函数,以避免代码中的大量重复.

我的问题是,对于某些图表,我使用的是+ facet_wrap()选项,但对于其他图表,我不是.即我需要facet wrap作为可选参数.当包含它时,代码需要使用facets参数中提供的变量调用+ facet_wrap().

理想情况下,我的函数看起来像这样,facet是一个可选参数:

$ qhist(variable, df, heading, facets)
Run Code Online (Sandbox Code Playgroud)

我已经尝试使用谷歌搜索如何添加可选参数,他们建议传递一个默认值或使用带有missing()函数的if循环.我无法上班.

这是我编写的函数,包含了可选facet参数的所需功能.

$ qhist <- function(variable, df, heading, facets) {
      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
      + facet_wrap(~ facets)
Run Code Online (Sandbox Code Playgroud)

JD *_*ong 11

设置默认值的方法如下:

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)
}
Run Code Online (Sandbox Code Playgroud)

*编辑*

哦,好吧......所以我想我对你的要求有了更好的了解.看起来你不确定如何将可选的facet引入ggplot对象.这个怎么样:

  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)
  }
Run Code Online (Sandbox Code Playgroud)

我根本没有测试过这段代码.但是一般的想法是facet_wrap需要一个公式,所以如果facets作为字符串传递,你可以用as.formula()它构建一个公式,然后将它添加到plot对象中.

如果我这样做,我会让函数接受一个可选的facet公式,然后将该facet公式直接传递给facet_wrap.这样就无需as.formula()调用将文本转换为公式.