R语言 使用map2在Shiny中生成多个图表不起作用

xggvc2p6  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(106)

这是我的代码:

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图表。
有人帮忙吗?

wqsoz72f

wqsoz72f1#

因为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))   
  
}

相关问题