我正在围绕某个包中的函数编写包装函数。该函数基本上为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-08-28。
答案 0 :(得分:2)
尝试一下:
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)
}
}
还意识到您可以添加ggtheme
而无需eval()
...
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
}
}