library(ggplot2)
library(dplyr)
plotfcn <- function(df, x, y, facet, fancy_labs){
# Strings of x & y (for axis titles)
xStr <- fancy_labs(deparse(substitute(x)))
yStr <- fancy_labs(deparse(substitute(y)))
#base plot
p <- ggplot(df, aes({{x}}, {{y}})) +
geom_point()
#add facets (with labels) and axis labels
p + facet_wrap(vars({{facet}}), labeller=fancy_labs) +
labs(x=xStr, y=yStr)
}
mylabs <- as_labeller(c(
'compact' = 'Small Family Car',
'midsize' = 'Medium Family Car',
'minivan' = 'For the Kids',
'pickup' = 'For the Stuff',
'displ' = 'Engine Displacement (L)',
'hwy' = 'Highway Mileage (mpg)'))
classlist <- c('compact', 'midsize', 'minivan', 'pickup')
mpg_lim <- mpg %>% filter(class %in% classlist)
mpg_lim %>% plotfcn(displ, hwy, class, fancy_labs = mylabs)
现在我想让标签者参数可选。将涉及标签的任何内容包装在if/else语句中很容易:
plotfcn <- function(df, x, y, facet, fancy_labs=NULL){
# Strings of x & y (for axis titles)
if(!is.null(fancy_labs)) {
xStr <- fancy_labs(deparse(substitute(x)))
yStr <- fancy_labs(deparse(substitute(y)))
}
#base plot
p <- ggplot(df, aes({{x}}, {{y}})) +
geom_point()
#optional: add labels using labeller
if(!is.null(fancy_labs)) {
p +
facet_wrap(vars({{facet}}), labeller=fancy_labs) +
labs(x=xStr, y=yStr)
} else {
p + facet_wrap(vars({{facet}}))
}
}
mpg_lim %>% plotfcn(displ, hwy, class, fancy_labs = mylabs)
mpg_lim %>% plotfcn(displ, hwy, class)
,如果可能的话,我想避免将facet_wrap()参数放入if/else语句中。 (在我的真实代码中,它已经在一个if/else序列中,因此添加此额外的if/else会添加很多分支和重复的复制/粘贴,这很麻烦。构造将Labeller参数传递给Facet_wrap,它运行良好 - 除了我不知道如何调用轴标签的同一标记函数。如下所示,我是否需要将相同的参数传递给我的代码两次,或者有任何方法可以通过椭圆构建和在我的代码中独立调用标签者参数?
plotfcn <- function(df, x, y, facet, fancy_labs=NULL, ...){
# Strings of x & y (for axis titles)
if(!is.null(fancy_labs)) {
xStr <- fancy_labs(deparse(substitute(x)))
yStr <- fancy_labs(deparse(substitute(y)))
}
#base plot - calls labeller using ...
p <- ggplot(df, aes({{x}}, {{y}})) +
geom_point() +
facet_wrap(vars({{facet}}), ...)
#optional: add labels using labeller
if(!is.null(fancy_labs)) {
p + labs(x=xStr, y=yStr)
} else {
p
}
}
#this works, but involves calling the same parameter (mylabs) twice under two different names, which is annoying
mpg_lim %>% plotfcn(displ, hwy, class, fancy_labs = mylabs, labeller=mylabs)
mpg_lim %>% plotfcn(displ, hwy, class)
如果我用一个标记的参数设置了该函数,则省略号构造不会触发,并且我的方面没有标记。但是,如果我只用椭圆设置了它,我将无法使用
function(df, x, y, facet, labeller = NULL, ...)
或
function(df, x, y, facet, ...)
触发我的if语句检查它的存在。有什么办法可以获取IF语句以识别标记参数的存在/不存在?
您可以使用
is.null()
来拉出并处理特定参数:
missing()