Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create plots based on radio button selection R Shiny

Tags:

plot

r

shiny

I'm trying to create a Shiny App. The user interface UI.R looks just fine but I'm having issues with server.R. Basically I want a different plot output depending on which radio option the user selects.

The user may choose option A, B, or C. I want to draw a histogram if user selects option A, bar graph for B, and a pie chart for option C but I don't know how to code the condition? Is it like an if-else statement? I've been struggling for hours! Here's my code sample:

output$plots <- renderPlot({    
   if selection == 'A'
      # plot histogram
   if selection == 'B'
      # plot bar chart
   if selection == 'C'
      # plot pie chart
})

Thanks!

like image 539
Tavi Avatar asked Sep 02 '14 22:09

Tavi


Video Answer


1 Answers

You can use switch to determine the behaviour based on the selection:

library(shiny)
myData <- runif(100)
plotType <- function(x, type) {
  switch(type,
         A = hist(x),
         B = barplot(x),
         C = pie(x))
}
runApp(list(
  ui = bootstrapPage(
    radioButtons("pType", "Choose plot type:",
                 list("A", "B", "C")),
    plotOutput('plot')
  ),
  server = function(input, output) {
    output$plot <- renderPlot({ 
       plotType(myData, input$pType)
    })
  }
))
like image 143
jdharrison Avatar answered Sep 27 '22 19:09

jdharrison