使用数据框设置shiny的selectInput

6

我希望通过使用数据框来设置selectInput中的选项。以下是一个示例,它可以工作并提供了选项“Peter”、“Bill”和“Bob”,但我希望这些选项是标签,并从L1Data$ID_1中设置值。通常情况下,这需要编写如下代码:

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

有没有关于获取此功能的建议?

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) )
    })
})

尝试 factor(unique(L1Data$Desc_1),labels=<...>, levels=<....>) - Ananta
1个回答

12

你应该创建一个命名向量来设置selectInput函数的choices参数。

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

您可以检查结果:

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>

1
我认为现在已经可以工作了,但我想要更多关于如何检查结果的信息。我没有通过shiny使用普通的HTML代码,你能否请解释一下我应该把它放在哪里(无论是在ui.R还是server.R中)。谢谢。 - gabrown86

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接