R-如何将一个函数作为参数传递给另一个函数?

时间:2019-03-28 20:07:11

标签: r function ggplot2

我有一个正在创建的函数,如下所示:

library(ggplot2)
plot_function <- function(data, x, y){
  ggplot(data, aes_string(x=x, y=y)) + 
    geom_line() + 
    scale_y_continuous(labels = scales::comma_format())
}

我可以这样称呼它:

df <- data.frame(date = seq(as.Date("2019/01/01"), as.Date("2019/01/05"),"1 day"), 
                 value = seq(.1,.5, .1))

df  

date        value      
2019-01-01    0.1         
2019-01-02    0.2         
2019-01-03    0.3         
2019-01-04    0.4 
2019-01-05    0.5

plot_function(df, x = "date", "value")

enter image description here

但是,如果我希望允许用户将y轴更改为百分比,该怎么办?如何让他们替换scales::comma_format()?这不起作用:

plot_function <- function(data, x, y, y_format){

  ggplot(data, aes_string(x=x, y=y)) + 
    geom_line() + 
    scale_y_continuous(labels = y_format)
}

plot_function(df, x = "date", "value", y_format = "scales::percent_format()")

我收到此错误:

"Error in f(..., self = self) : Breaks and labels are different lengths"

2 个答案:

答案 0 :(得分:3)

另一种选择是使用...参数设置函数,以便将labels参数传递给scale_y_continuous是可选的:

plot_function <- function(data, x, y, ...) {

  ggplot(data, aes_string(x=x, y=y)) + 
    geom_line() + 
    scale_y_continuous(...)
}

# Pass nothing to scale_y_continuous
plot_function(mtcars, x = "cyl", y="hp")

# Add some big numbers to mtcars
mtcars$hp = 1e5 * mtcars$hp

# Pass a labels argument to scale_y_continuous to get comma formatted values
plot_function(mtcars, x = "cyl", y="hp", labels=scales::comma)

答案 1 :(得分:2)

尝试一下:

plot_function <- function(data, x, y, y_format){

 ggplot(data, aes_string(x=x, y=y)) + 
 geom_line() + 
  scale_y_continuous(labels = y_format())

}

plot_function(df, x = "date", "value", y_format = scales::percent_format)