使用highcharter函数内部

问题描述 投票:3回答:1

如何使用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

r highcharts r-highcharter
1个回答
4
投票

我们需要使用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)

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"
  )
} 
© www.soinside.com 2019 - 2024. All rights reserved.