Save a checkboxGroupInput choice and put it in a conditional to continue R code base.

Here is an example of my issue. I would like to save the selection of the checkboxGroupInput and then use the answer to assign values to a variable which I will use in the rest of the code.

library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
   
  # Application title
  titlePanel("Example"),
  
  # Sidebar with a slider input for number of bins 
  sidebarLayout(
    sidebarPanel(
         
         checkboxGroupInput("items","Which Item?",
                            choices=c("A","B","C","D")),
         
         submitButton(
           text = "Guardar",
           icon = icon("sliders"), 
           width ='200px')),
        
         mainPanel(
           verbatimTextOutput(      
             outputId = "text"),
           verbatimTextOutput(          
             outputId = "letter")
           
         )
    )
  )
# Define server logic required to draw a histogram
server <- function(input, output) {
   
  election<-reactive(input$items)
  if(election()=='D'){
    D<-reactive(1)
  }else{
    D<-reactive(0)
  }
  if(D()==1){
    sd<-1
  }else{
    sd<-0
  }
  
  output$text<-renderPrint( election() )
  output$letter<-renderPrint(sd)
}

# Run the application 
shinyApp(ui = ui, server = server)

So for example, I "turn on" or "turn off" the D variable, and according to that, continue with the rest of the code. Is not necessary to print something, I wrote that just for try to see what happens.
The error I get is:
Error in .getReactiveEnvironment()$currentContext() :
Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

I have read about this on the internet but I haven't solved this yet. Please help! u.u

library(shiny)

ui <- fluidPage(
  titlePanel("Example"),
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput("items", "Which Item?",
        choices = c("A", "B", "C", "D")
      ),
    ),
    mainPanel(
      verbatimTextOutput(
        outputId = "text"
      ),
      verbatimTextOutput(
        outputId = "letter"
      ))))

server <- function(input, output) {
  election <- reactive({
    if (isTruthy(input$items)) {
      return(input$items)
    } else {
      return("")
    }})

  # initial values
  sd <- reactiveVal("0")
  D <- reactiveVal(0)

  observeEvent(election(), {
    if ("D" %in% election()) {
      D(1)
    } else {
      D(0)
    }
    if (D() == 1) {
      sd("1")
    } else {
      sd("0")
    }
  })

  output$text <- renderPrint(election())
  output$letter <- renderPrint(sd())
}

shinyApp(ui = ui, server = server)
1 Like

Thank you for your time!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.