将可变名称传递给用户定义的函数,该功能使图表图表
我在将可变名称从共享数据集中传递给我定义的函数时遇到了麻烦。
我已经看到了针对类似R问题的文档,并试图实施一些解决方案,但无济于事。
在下面的reprex中,我遇到一个错误,说明“ eval(expr,data,expr_env)中的错误:对象'pct_increase'找不到的对象”
是否有解决方案?非常感谢。
reprex:
library(tidyverse)
library(plotly)
library(crosstalk)
bar_tibble <- tibble(category = c("Cat 1", "Cat 1", "Cat 2", "Cat 2"),
pct_increase = c(0.17, 0.25, 0.64, 0.85),
week = c(1, 2, 1, 2))
bar_data_shared <- SharedData$new(bar_tibble, ~week)
SharedData$origData(bar_tibble)
make_bar_chart <- function(shared_data, xvar, yvar){
plot_ly(data = shared_data, hoverinfo = "none") %>%
add_trace(
x = ~xvar,
y = ~yvar,
type = "bar",
transforms = list(
list(
type = "aggregate",
groups = ~yvar,
aggregations = list(
list(
target = "x", func = "avg", enabled = T)))))
}
make_bar_chart(bar_data_shared, pct_increase, category)
I'm having trouble with passing a variable name from a shared data set to a function I've defined.
I've seen documentation for similar R issues and have tried to implement some of the solutions to no avail.
In the reprex below, I encounter an error stating "Error in eval(expr, data, expr_env) : object 'pct_increase' not found"
Does anyone have a solution for this? Many thanks.
reprex:
library(tidyverse)
library(plotly)
library(crosstalk)
bar_tibble <- tibble(category = c("Cat 1", "Cat 1", "Cat 2", "Cat 2"),
pct_increase = c(0.17, 0.25, 0.64, 0.85),
week = c(1, 2, 1, 2))
bar_data_shared <- SharedData$new(bar_tibble, ~week)
SharedData$origData(bar_tibble)
make_bar_chart <- function(shared_data, xvar, yvar){
plot_ly(data = shared_data, hoverinfo = "none") %>%
add_trace(
x = ~xvar,
y = ~yvar,
type = "bar",
transforms = list(
list(
type = "aggregate",
groups = ~yvar,
aggregations = list(
list(
target = "x", func = "avg", enabled = T)))))
}
make_bar_chart(bar_data_shared, pct_increase, category)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用功能时,必须使用真实的对象或字符串。换句话说,您必须将列名作为字符串传递。
从那里您遇到了另一个问题。一旦使列名称绘制将不会将列连接到
sharedData
对象,而无需其他干预。由于我认为您不希望参数名称作为Axes的标签,因此我也添加了标签。
这是您可以做的工作。
When you call your function, you have to use real objects or strings. In other words, you have to pass the column names as strings.
From there you run into another issue. Once you make the column names strings Plotly will not connect columns to the
SharedData
object without additional intervention.Since I don't think you want the parameter name as the axes' labels, I added labels, as well.
Here is what you can do to make this work.