【问题标题】:getting function to work irrespective of whether argument has parentheses or not无论参数是否有括号,都可以使函数正常工作
【发布时间】:2018-08-29 00:15:08
【问题描述】:

我正在围绕某个包中的函数编写一个包装函数。该功能基本上为ggplot 对象添加了一个新主题。但是函数的实现方式,需要将主题参数指定为函数。但是我希望我的包装函数能够工作,而不管参数是指定为函数还是主题对象。我该怎么做?

这是一个关于函数的玩具示例,它的工作条件以及它不工作的条件:

# loading needed libraries
library(ggplot2)

# creating basic plot on which themes are to be added
plot <- ggplot(mtcars, aes(wt, mpg)) + geom_point()

# first attempt at the function
theme_adder1 <- function(ggplot.obj, ggtheme = ggplot2::theme_bw) {
  # this can't be modified (because it was written by someone else)
  ggplot.obj + ggtheme() 
}

# this works
theme_adder1(ggplot.obj = plot, ggtheme = ggplot2::theme_grey)

# this doesn't work
theme_adder1(ggplot.obj = plot, ggtheme = ggplot2::theme_grey())
#> Error in ggtheme(): could not find function "ggtheme"

# checking classes
class(ggplot2::theme_bw())
#> [1] "theme" "gg"
class(ggplot2::theme_bw)
#> [1] "function"

所以我想知道是否有某种方法可以将ggtheme 对象(当作为theme 对象输入时)转换为function 对象然后使用。但我不知道该怎么做。

# second attempt at modifying function in a way that it will work irrespective
# of how the ggtheme argument is entered
theme_adder2 <- function(ggplot.obj, ggtheme = ggplot2::theme_bw) {
  if (class(ggtheme)[[1]] == "function") {
    ggplot.obj + ggtheme()
  } else if (class(ggtheme)[[1]] == "theme") {
    # what modifcation can be made here?
    ggtheme <- ??? 
    ggplot.obj + ggtheme()
  }
}

reprex package (v0.2.0.9000) 于 2018 年 8 月 28 日创建。

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    试试这个:

    theme_adder2 <- function(ggplot.obj, ggtheme = ggplot2::theme_bw) {
      if (class(ggtheme)[[1]] == "function") {
        ggplot.obj + ggtheme()
      } else if (class(ggtheme)[[1]] == "theme") {
        # what modifcation can be made here?
          ggplot.obj + eval(ggtheme)
      }
    }
    

    也刚刚意识到你可以在没有eval() 的情况下添加ggtheme...

    theme_adder2 <- function(ggplot.obj, ggtheme = ggplot2::theme_bw) {
      if (class(ggtheme)[[1]] == "function") {
        ggplot.obj + ggtheme()
      } else if (class(ggtheme)[[1]] == "theme") {
        # what modifcation can be made here?
          ggplot.obj + ggtheme
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      • 2018-09-05
      • 2019-01-04
      相关资源
      最近更新 更多