在函数中使用 highcharter

Use highcharter inside a function

如何在函数中使用 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() 捕获用户提供的作为参数的表达式 & returns 一个 quosure。
  • quo_name() 压缩 quosure 并将其转换为字符串。

观看 Hadley 在此 5min video if you haven't heard about it. More on tidyeval here

中解释 tidyeval
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"
  )
}