在函数内部使用highcharter

时间:2018-03-13 18:40:18

标签: r highcharts r-highcharter

如何在函数中使用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中找到有关类似功能的任何文档。

image of highcharter line graph enter image description here

1 个答案:

答案 0 :(得分:2)

我们需要使用enquo()&amp; quo_name()以及hcaes_string

  • enquo()捕获用户提供的作为参数的表达式&amp;返回一个结果。
  • quo_name()压缩quosure并将其转换为字符串。

观看Hadley在5min video中解释tidyeval,如果您还没有听说过它。有关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)

enter image description here

修改:自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"
  )
}