Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
891 views
in Technique[技术] by (71.8m points)

create plots based on radio button selection 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...