你能在函数名中使用参数吗?

问题描述 投票:0回答:1
我正在编写一个使用给定数据生成

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
    
r metaprogramming tidyeval nse
1个回答
1
投票
不需要tidyeval。您可以使用

getExportedValue

 在命名空间中查找名称;所以要找到
scales::label_X
,你可以使用
getExportedValue("scales", "label_X")

label_function <- getExportedValue("scales", glue::glue("label_{label}"))
对于非限定名称(即如果您前面没有

scales::

),您可以改用
get(name, mode = "function")

© www.soinside.com 2019 - 2024. All rights reserved.