在函数内使用highcharter [英] Use highcharter inside a function
问题描述
如何使用 highcharter ::
How do I use highcharter::hchart inside a function?
这是使用hchart
函数的简单折线图.
Here is a simple line graph using the hchart
function.
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")
当我尝试编写函数来创建相同的图形时,出现错误.
When I try to write a function to create the same graph I get an error.
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()
的东西(
When I traceback the error it seems hchart
is using dplyr::mutate_
. This leads me to believe the error has something to do with NSE and maybe hchart
needs something akin to ggplot2::aes_string()
(link). However, I can't find any documentation on a similar function in highcharter
.
推荐答案
我们需要使用enquo()
& quo_name()
和hcaes_string
We need to use enquo()
& quo_name()
together with hcaes_string
-
enquo()
捕获用户&作为参数提供的表达式.返回担保. -
quo_name()
压缩quasure并将其转换为字符串.
enquo()
captures the expression supplied as argument by the user & returns a quosure.quo_name()
squashes the quosure and transforms it into a string.
Hadley观看者在此 5分钟视频中解释了tidyeval
(如果您没有听过的话). tidyeval
此处
Watch Hadley explained tidyeval
in this 5min video if you haven't heard about it. More on 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
可以重写为:
Edit: as of April 18, 2018, the development version of highcharter
supports tidyeval
so h_fun2
can be rewritten as:
h_fun2 <- function(df, x, y) {
x <- enexpr(x)
y <- enexpr(y)
hchart(df,
type = "line",
hcaes(!!x, !!y),
name = "Average Arrival Delay"
)
}
这篇关于在函数内使用highcharter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!