Search code examples
rshinyselectinput

selectizeinput reading column-name instead of value


can somebody explain this behavior to me? In R, if list l[[i]] contains only one element, selectizeinput shows only the column-name instead of the element. It doesn't include the column name if there are more elements.

In the console the behavior is also different between these 2:

> l[[1]][,'value']

            value 
    "some string" 


> l[[2]][,'value2']
[1] "more string"  "other string"

library(shiny)

l <- c()

value <- "some string"
id <- "1"
df <- cbind(id,value)
l[[1]] <- df

value2 <- c("more string", "other string")
id2 <- c("2","3")
df2 <- cbind(id2,value2)
l[[2]] <- df2

ui <- fluidPage(
  selectizeInput("input", "selectize 1", l[[1]][,'value'], multiple=TRUE),
  verbatimTextOutput("out"),
  selectizeInput("input2", "selectize 2", l[[2]][,'value2'], multiple=TRUE),
  verbatimTextOutput("out2")
)

server <- function(input,output){
  output$out <- renderText({
    input$input
  })
  output$out2 <- renderText({
    input$input2
  })
}

shinyApp(ui = ui, server = server)

Solution

  • I am not sure about the full details of why this happens but your first matrix stored it's value as Named chr instead of a chr as seen here:

    > str(l[[1]][, 'value'])
     Named chr "some string"
     - attr(*, "names")= chr "value"
    > str(l[[2]][, 'value2'])
     chr [1:2] "more string" "other string"
    

    You can solve this issue by reading the first matrix as a vector which will look like this in the ui:

    ...
    selectizeInput("input", "selectize 1", as.vector(l[[1]][,'value']), multiple=TRUE),
    ...