代码之家  ›  专栏  ›  技术社区  ›  Doug Fir

为选定的输入选项获取数据帧的唯一值,但仅当在server.ui中定义了数据帧而不是全局

  •  0
  • Doug Fir  · 技术社区  · 5 年前

    闪亮应用示例:

    library(tidyverse)
    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(
             sliderInput("bins",
                         "Number of bins:",
                         min = 1,
                         max = 50,
                         value = 30),
    
          selectInput(inputId = "cut",
                      label = "cut",
                      # choices =  unique(diamonds$cut), # works
                      choices =  unique(my_diamonds$cut), # does not work
                      selected = "Ideal")
    
          ),
    
          # Show a plot of the generated distribution
          mainPanel(
             plotOutput("distPlot")
          )
       )
    )
    
    # Define server logic required to draw a histogram
    server <- function(input, output) {
    
      my_diamonds <- diamonds
    
       output$distPlot <- renderPlot({
          # generate bins based on input$bins from ui.R
          x    <- my_diamonds$carat
          bins <- seq(min(x), max(x), length.out = input$bins + 1)
    
          # draw the histogram with the specified number of bins
          hist(x, breaks = bins, col = 'darkgray', border = 'white')
       })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    在这种情况下,我使用的是一个人造数据框“我的钻石”。在我的实际代码中,我使用dbplyr连接到一个数据库,然后对它进行一些转换,因此在ui部分复制它似乎是浪费。

    在本例中,使用服务器部分中定义的数据帧获取唯一值的“正确”方法是什么 my_diamonds$cut 要用作选定输入的下拉选择吗?

    1 回复  |  直到 5 年前
        1
  •  1
  •   Roshan Santhosh    5 年前

    您可以使用 UIoutput 在UI中,然后使用 renderUI .

    因此,假设您定义了一个UIOutput元素 otn_race_selection_op ,然后我们可以使用下面的代码将其定义为selectInput对象。这里的getData是一个反应元素,它将自己更新为最新的数据。基于此,您可以修改selectInput对象的输入选项

    
    output$otn_race_selection_op <- renderUI({
    
    
        df <- getData() 
    
        options <- sort(unique(df$Race))
    
        selectInput(
          inputId = "otn_race_selection",
          label = "Race",
          choices = c("All", options)
          ,
          selected = "All"
        )
    
      })