Laura
Laura

Reputation: 513

Generating multiple charts in Shiny with map2 is not working

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?

Upvotes: 0

Views: 42

Answers (1)

MrFlick
MrFlick

Reputation: 206242

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

Upvotes: 1

Related Questions