gpt4 book ai didi

r - 使用 dplyr 进行问题编程——列绝对是一个被选取为公式的向量

转载 作者:行者123 更新时间:2023-12-03 16:47:46 24 4
gpt4 key购买 nike

我正在编写一个函数来使用 highcharter 重现几个图表,这些图表都将具有类似的格式(和其他内容)。如果名称发生变化,或者如果我想做一些不同的事情,我希望能够选择数据集的不同列,并且我正在接受这些参数 {{ }} .但是后来我收到了这个奇怪的错误:

Error: Problem with `mutate()` input `x`.
x Input `x` must be a vector, not a `formula` object.
i Input `x` is `~Year`.
这是我的(最小可重现)代码:
library(dplyr)
library(highcharter)

plot_high_chart <- function(.data,
chart_type = "column",
x_value = Year,
y_value = total,
group_value = service) {
.data %>%
hchart(chart_type, hcaes(x = {{x_value}}, y = {{y_value}}, group = {{group_value}}))
}

data %>% plot_high_chart()
这是 dput数据结果:
structure(list(Year = c(2016, 2017, 2017, 2018, 2018, 2018), 
service = structure(c(10L, 3L, 9L, 5L, 7L, 9L), .Label = c("Defense Logistics Agency",
"Chemical and Biological Defense Program", "Defense Information Systems Agency",
"United States Special Operations Command", "Office of the Secretary Of Defense",
"Missile Defense Agency", "Defense Advanced Research Projects Agency",
"Navy", "Army", "Air Force"), class = "factor"), total = c(9.435,
0, 10.442, 9.969, 73.759, 8.855)), row.names = c(NA, -6L), groups = structure(list(
Year = c(2016, 2017, 2018), .rows = structure(list(1L, 2:3,
4:6), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, 3L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

最佳答案

{{a}}!!enquo(a) 的简写,它捕获提供给 a 的表达式以及应评估此表达式的上下文。在您的情况下,上下文是已经提供给函数的数据框。所以,更好的 rlang这里使用的动词是 ensym(a) ,它捕获提供给 a 的符号名称反而:

plot_high_chart <- function(.data,
chart_type = "column",
x_value = "Year", # <-- Note: strings
y_value = "total",
group_value = "service") {
.data %>%
hchart(chart_type, hcaes(x = !!rlang::ensym(x_value), # <- ensym instead of {{
y = !!rlang::ensym(y_value),
group = !!rlang::ensym(group_value)))
}
作为奖励,该函数现在可以处理符号和字符串:
data %>%
plot_high_chart(x_value= "Year", y_value= "total", group_value= "service") # Works
data %>%
plot_high_chart(x_value= Year, y_value= total, group_value= service) # Also Works

关于r - 使用 dplyr 进行问题编程——列绝对是一个被选取为公式的向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64391305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com