Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting shiny selectInput from data.frame

Tags:

r

shiny

I am wanting to set the choices within selectInput using a data frame. Below I have an example of it working, and this gives the choices "Peter", "Bill" and "Bob", but I would like these to be the label, and to set the value from L1Data$ID_1. Something that would normally be coded up using:

    selectInput("partnerName", "Select your choice",  c("Peter" = "15","Bob" = "25","Bill" = "30" ) )

Any suggestions for getting this functionality?

ui.R

library(shiny)
shinyUI(pageWithSidebar(
  headerPanel("Test App"),
  sidebarPanel(
  sliderInput("obs", "Number of observations:", min = 1, max = 1000, value = 500),

  htmlOutput("selectUI")
  ),
 mainPanel(
    plotOutput("distPlot")
  )
))

server.R

library(shiny)
ID_1 <- c(15,25,30,30)
Desc_1 <- c("Peter","Bob","Bill","Bill")
L1Data <- data.frame(ID_1,Desc_1)
shinyServer(function(input, output) {
  output$distPlot <- renderPlot({
    dist <- rnorm(input$obs)
    hist(dist)
  })
  output$selectUI <- renderUI({ 
    selectInput("partnerName", "Select your choice",  unique(L1Data$Desc_1) )
    })
})
like image 707
gabrown86 Avatar asked Jan 02 '14 16:01

gabrown86


1 Answers

You should create a named vector to set choices argument of selectInput function.

choices = setNames(L1Data$ID_1,L1Data$Desc_1)
si <- selectInput("partnerName", "Select your choice",  choices)

You can check the result:

cat(as.character(si))
<label class="control-label" for="partnerName">Select your choice</label>
<select id="partnerName">
  <option value="15" selected="selected">15</option>
  <option value="25">25</option>
  <option value="30">30</option>
  <option value="30">30</option>
</select>
like image 122
agstudy Avatar answered Oct 15 '22 13:10

agstudy