如何使用highcharter :: hchart一个函数里?
下面是使用hchart
函数的简单线性图。
library(tidyverse)
library(lubridate)
library(highcharter)
library(nycflights13)
flights_2 <- flights %>%
mutate(dep_mo = ymd(str_c(year, month, "01", sep = "-"))) %>%
group_by(dep_mo) %>%
summarize(arr_delay = mean(arr_delay, na.rm = TRUE))
hchart(flights_2,
type = "line",
hcaes(x = dep_mo, y = arr_delay),
name = "Average Arrival Delay")
当我尝试写一个函数来创建相同的图形,我得到一个错误。
h_fun <- function(df, x, y) {
hchart(df,
type = "line",
hcaes(x = x, y = y),
name = "Average Arrival Delay"
)
}
h_fun(df = flights_2, x = dep_mo, y = arr_delay)
这是错误消息:Error in mutate_impl(.data, dots) : Binding not found: x.
当我回迹错误似乎hchart
使用dplyr::mutate_
。这使我相信错误有事情做与NSE,也许hchart
需要ggplot2::aes_string()
(link)某种类似。但是,我找不到在highcharter
类似功能的任何文档。
我们需要使用enquo()
及与quo_name()
一起hcaes_string
enquo()
由用户捕获作为参数提供的表达式&返回quosure。quo_name()
南瓜的quosure并将其转换为一个字符串。观看哈德利在此tidyeval
解释5min video如果你还没有听说过。更多关于tidyeval
here
library(tidyverse)
library(lubridate)
library(highcharter)
library(nycflights13)
flights_2 <- flights %>%
mutate(dep_mo = ymd(str_c(year, month, "01", sep = "-"))) %>%
group_by(dep_mo) %>%
summarize(arr_delay = mean(arr_delay, na.rm = TRUE))
h_fun2 <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
hchart(df,
type = "line",
hcaes_string(quo_name(x), quo_name(y)),
name = "Average Arrival Delay"
)
}
h_fun2(df = flights_2, x = dep_mo, y = arr_delay)
编辑:作为2018年4月18日的,highcharter
的开发版本支持tidyeval
所以h_fun2
可以改写为:
h_fun2 <- function(df, x, y) {
x <- enexpr(x)
y <- enexpr(y)
hchart(df,
type = "line",
hcaes(!!x, !!y),
name = "Average Arrival Delay"
)
}