ggplot
s 的函数,我有兴趣设置一个可以调用不同
scales::label_*
函数来更改输出的参数。例如,我希望能够调用
create_pie_chart(starwars, fill = gender, label = "percent")
并使用
scales::label_percent
或
create_pie_chart(starwars, fill = gender, label = "date")
显示标签,并让标签使用
scales::label_date
.我知道我可以只使用一些 if else 语句,但我很好奇是否有整洁的 eval 或 NSE 方法来做到这一点?也许使用
substitute
或
{{}}
?这是一个示例,我尝试使用
glue
创建函数名称——它不起作用:
library(dplyr)
create_pie_chart <- function(data,
fill,
label = "percent") {
data_counts <- data %>%
dplyr::summarize(num = dplyr::n(), .by = {{ fill }}) %>%
dplyr::mutate(prop = num/sum(num))
label_function <- glue::glue("scales::label_", label)
plot <- data_counts %>%
ggplot2::ggplot(ggplot2::aes(x="", y = prop, fill = {{ fill }})) +
ggplot2::geom_bar(width = 1, stat = "identity") +
ggplot2::coord_polar("y", start = 0) +
ggplot2::geom_label(
# This is the line where I would like to use tidy eval
# to call `scales::label_*` with my `label` parameter
ggplot2::aes(label = label_function()(prop)),
position = ggplot2::position_stack(vjust = 0.5)
) +
ggplot2::theme_void()
plot
}
data("starwars")
create_pie_chart(starwars, fill = gender, label = "percent")
我也试过match.fun
/
get(..., mode = function)
如this question中所述,但我得到一个错误说明:
Error in get(as.character(FUN), mode = "function", envir = envir) :
object 'scales::label_percent' of mode 'function' was not found
getExportedValue
在命名空间中查找名称;所以要找到
scales::label_X
,你可以使用
getExportedValue("scales", "label_X")
:
label_function <- getExportedValue("scales", glue::glue("label_{label}"))
对于非限定名称(即如果您前面没有scales::
),您可以改用
get(name, mode = "function")
。