Search code examples
rcheckboxshinyshinydashboard

checkboxinput server issues in R


I want to have a checkbox in my UI that will act as an if statement in my server but I'm not sure how to properly code the part in the server. In this example, I would like the graph to output when the box is checked.

Here is my code

ui <- fluidPage(

    titlePanel("title"),

    sidebarLayout(
        sidebarPanel(
            checkboxInput("EF", "Efficient Frontier")
        ),

        mainPanel(
            fluidRow(
                align = "center",
                plotOutput("Graphw")
            )
        )
    )
)

server <- function(input, output) {
    
                if(input$EF){
                    X <- function(a,b,c){
                        plot(c(a,b),c(b,c))
                         }
                }
    
                OPw <- reactiveValues()
                OPw$PC <- X(5,10,15)
                
                output$Graphw <- renderPlot({ 
                    OPw$PC
                })
}

shinyApp(ui = ui, server = server)

I need to add some kind of reactive values but Im not sure where. Any help would be appreciated


Solution

  • I think you can do this without using reactiveValues. Make the function X as independent function which can be called under renderPlot.

    library(shiny)
    
    X <- function(a,b,c){
      plot(c(a,b),c(b,c))
    }
    
    ui <- fluidPage(
      
      titlePanel("title"),
      
      sidebarLayout(
        sidebarPanel(
          checkboxInput("EF", "Efficient Frontier")
        ),
        
        mainPanel(
          fluidRow(
            align = "center",
            plotOutput("Graphw")
          )
        )
      )
    )
    
    server <- function(input, output) {
      
      output$Graphw <- renderPlot({ 
        if(input$EF){
          X(5,10,15)
        }
      })
    }
    
    shinyApp(ui = ui, server = server)
    

    enter image description here