upendra
upendra

Reputation: 2189

How to interact with a checkbox in shiny R?

I am having hard time interacting the checkbox option in R shiny. What i want is if the user choses the checkbox option, the graph should be a different one compared to the non-check ones. However i cannot get it to work even though i have tried several times

ui.R

library(shiny)
library(ggplot2)

shinyUI(fluidPage(

  # Application title
  titlePanel("Demonstration of 2 dropdown menus"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      selectInput("element_id1", "select variable for x-axis", c("mpg", "cyl", "disp", "hp", "wt"), selected = "wt"),
      selectInput("element_id2", "select variable for x-axis", c("mpg", "cyl", "disp", "hp", "wt"), selected = "mpg"),
      checkboxGroupInput("variable", "Variable:", c("stat_smooth()"))
    ),

    # Show a plot of the generated distribution
    mainPanel(h3("Outputs"),
      textOutput("id1"),
      textOutput("id2"),
      plotOutput("plt")
    )
  )
))

server.R

library(shiny)
library(ggplot2)

shinyServer(function(input, output) {
  output$id1 <- renderText({
    sprintf("You have selected %s on the x-axis", input$element_id1)
})
  output$id2 <- renderText({
    sprintf("You have selected %s on the y-axis", input$element_id2)
  })
  output$plt <- renderPlot(
    ggplot(mtcars, aes_string(x = input$element_id1, y = input$element_id2)) + geom_point() + ggtitle("ggplot"),

    if(input$variable) {
      ggplot(mtcars, aes_string(x = input$element_id1, y = input$element_id2)) + geom_point() + geom_smooth() + ggtitle("ggplot")
    } 
  )
})

Upvotes: 1

Views: 4982

Answers (1)

Kirill
Kirill

Reputation: 391

Your server.R has unmatching opeing ({ characters and misplaced commas.

I fixed it:

library(shiny)
library(ggplot2)

shinyServer( function(input, output) {
  output$id1 <- renderText({
    sprintf("You have selected %s on the x-axis", input$element_id1)
  })

  output$id2 <- renderText({
    sprintf("You have selected %s on the y-axis", input$element_id2)
  })

  output$plt <- renderPlot({
    ggplot(mtcars, aes_string(x = input$element_id1, y = input$element_id2)) + geom_point() + ggtitle("ggplot")
    if(input$variable) {
      ggplot(mtcars, aes_string(x = input$element_id1, y = input$element_id2)) + geom_point() + geom_smooth() + ggtitle("ggplot")
    } 
  })

})

Reactivity seems to work, now you have to fix your data.

Cheers

Upvotes: 1

Related Questions