Я пишу функцию-оболочку для функции из некоторого пакета. Функция в основном добавляет новую тему к 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()
}
}
Создано в 2018-08-28 пакетом Представ (v0.2.0.9000).