Jorge Hernández
Jorge Hernández

Reputation: 662

Error when trying to update selections from a pickerinput

Hello and thanks for the help. I am trying to make an app that updates the selections of one pickerinput depending on the selections of another. The idea is that if one pickerinput has something selected then the other removes all current selections (and vice versa), but I get an error when trying to update the pickerinputs

My code is the following:

library(shiny)
library(shinywidgets)

var1 <- c(1,2,3,4,1,2,3)
var2 <- c(1,2,3,3,1,2,2,1,2,1)

shinyApp(
  ui = fluidPage(
    pickerInput("primero", 
                "opciones a escoger", 
                choices = var1,
                selected = var1,
                multiple = TRUE
                ),
    pickerInput("segundo", 
                "opciones a escoger 2", 
                choices = var2,
                multiple = TRUE
    )
  ),
  server = function(input, output, session){
    
    
    valor <- reactive({
     c( input$primero)
    })
    
   observeEvent(input$primero,{
     req(valor())
     updatePickerInput(session,"segundo",
                       choices = var2,
                       selected = 
                         if_else(length(valor())>0, NULL, head(var2,1))
                       )
     
   }) 
    
  }
)

Error message:

Warning: Error in : `false` must be NULL, not a double vector.
  [No stack trace available]

Any ideas for suggestions? Thanks a lot

Upvotes: 0

Views: 101

Answers (1)

r2evans
r2evans

Reputation: 160447

if_else requires that the class/type of both its second and third arguments must be the same. Further, since it is intended to be a vectorized logical if/else, having one of them be NULL does not make sense.

Looking more at the code, you are using it incorrectly: do not assume that it (or base::ifelse) is a drop-in replacement for if/else, they are very much different. Replace your observeEvent with:

   observeEvent(input$primero,{
     req(valor())
     updatePickerInput(session,"segundo",
                       choices = var2,
                       selected =
                         if (!length(valor()) > 0) head(var2, 1)
                       )
     
   }) 

I'm shortcutting it slightly here: when we have if and no else, when the conditional evaluates to FALSE then it returns NULL, which is what I think your if_else(length(valor()) > 0, NULL, ..) meant.

Upvotes: 1

Related Questions