3

如何在函数中使用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()链接)的东西。但是,我在highcharter.

在此处输入图像描述

4

1 回答 1

5

我们需要与enquo()&quo_name()一起使用hcaes_string

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

如果您还没有听说过,请观看tidyeval​​段 5 分钟视频中的Hadley 解释。更多关于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重写为:tidyevalh_fun2

h_fun2 <- function(df, x, y) {
  x <- enexpr(x)
  y <- enexpr(y)
  hchart(df, 
         type = "line",
         hcaes(!!x, !!y),
         name = "Average Arrival Delay"
  )
} 
于 2018-03-13T19:26:35.180 回答