英文:
Generating multiple charts in Shiny with map2 is not working
问题
这是我的代码:
library(shiny)
library(gapminder)
ui <- fluidPage(
highchartOutput(outputId = 'chart_1'),
highchartOutput(outputId = 'chart_2'),
highchartOutput(outputId = 'chart_3')
)
server <- function(input, output, session) {
data <- gapminder::gapminder %>% filter(country == 'Chile')
function_chart <- function(x, z) {
output[[paste0('chart_', x)]] <- renderHighchart({
hchart(
data,
'column',
hcaes(x = year,
y = data[[z]]),
colorByPoint = TRUE
)
})
}
map2(1:3, c('pop', 'lifeExp', 'gdpPercap'), ~ function_chart(x = .x, z = .y))
}
shinyApp(ui, server)
错误可能在'function_chart'
函数中,特别是当调用参数z
时。输出应该为3个Highchart图表。需要帮助吗?
英文:
This is my code:
library(shiny)
library(gapminder)
ui <- fluidPage(
highchartOutput(outputId = 'chart_1'),
highchartOutput(outputId = 'chart_2'),
highchartOutput(outputId = 'chart_3')
)
server <- function(input, output, session) {
data <- gapminder::gapminder %>% filter(country == 'Chile')
function_chart <- function(x,z) {
output[[paste0('chart_', x)]] <- renderHighchart({
hchart(
data,
'column',
hcaes(x = year,
y = data[[z]]),
colorByPoint = TRUE
)
})
}
map2(1:3,c('pop','lifeExp','gdpPercap'),~ function_chart(x = .x, z = .y))
}
shinyApp(ui, server)
The error is in the function 'function_chart'
probably when I call the argument z
. The output should give me 3 highchart charts.
Any help?
答案1
得分: 1
因为hcaes
是惰性评估的,你需要用!!
将当前值"z"注入其中。试试:
server <- function(input, output, session) {
data <- gapminder::gapminder %>% filter(country == 'Chile')
function_chart <- function(x,z) {
output[[paste0('chart_', x)]] <- renderHighchart({
hchart(
data,
'column',
hcaes(x = year,
y = !!z),
colorByPoint = TRUE
)
})
}
map2(1:3,c('pop','lifeExp','gdpPercap'),~ function_chart(x = .x, z = .y))
}
英文:
Because hcaes
is lazy evaluated, you need to inject the current value of "z" in there with !!
. Try
server <- function(input, output, session) {
data <- gapminder::gapminder %>% filter(country == 'Chile')
function_chart <- function(x,z) {
output[[paste0('chart_', x)]] <- renderHighchart({
hchart(
data,
'column',
hcaes(x = year,
y = !!z),
colorByPoint = TRUE
)
})
}
map2(1:3,c('pop','lifeExp','gdpPercap'),~ function_chart(x = .x, z = .y))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论