代码之家  ›  专栏  ›  技术社区  ›  Loyushka

selectInput的值列表

  •  2
  • Loyushka  · 技术社区  · 7 年前

    我想创建一个“selectInput”小部件,其中值的选择是由“fileInput”小部件导入的数据集中的列的名称。

    library(shiny)
    
    ui <- fluidPage(
    
      # Widget for loading data set
      fileInput("file", label = h4("Input csv data set")),
    
      # Widget for selecting the variable among names of columns of the data set
      selectInput("select.variable", label = h4("Select variable from data set"),
      choices = tableOutput("list.var"), selected = 1) # This approach doesn't work
    
      )
    
    server <- function(input, output) {
    
      # The goal was to get the list of names of columns to use it as "choices"
      # in the "selectInput" widget
      output$list.var <- renderTable({
    
      inFile <- input$file
      if (is.null(inFile)) # To avoid error messages when the file is not yet loaded
      return(NULL)
    
      # After the file is loaded
      data.fr <- read.csv(inFile$datapath)
      list.var <- names(data.fr[1,]) # Get the names of the columns of the dataset
    
      })
    
      }
    
    shinyApp(ui = ui, server = server)
    

    有没有办法使用导入数据集的列名称作为“selectInput”小部件的选项?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Pork Chop    7 年前

    像这样的事情应该会奏效。我用过 renderUI

    library(shiny)
    
    ui <- fluidPage(
    
            # Widget for loading data set
            fileInput("file", label = h4("Input csv data set")),
            uiOutput("myslider")
    )
    server <- function(input, output) {
    
            # The goal was to get the list of names of columns to use it as "choices"
            # in the "selectInput" widget
    
            output$myslider <- renderUI({
                    # Widget for selecting the variable among names of columns of the data set
                    selectInput("select.variable", label = h4("Select variable from data set"),
                                choices = names(mydata()), selected = 1) # This approach doesn't work 
    
            })
    
            mydata <- reactive({
                    inFile <- input$file
                    if (is.null(inFile)) # To avoid error messages when the file is not yet loaded
                            return(NULL)
    
                    # After the file is loaded
                    data.fr <- read.csv(inFile$datapath)
                    names(data.fr[1,]) # Get the names of the columns of the dataset  
            })
    
            output$list.var <- renderTable({
                    mydata()
            })
    
    }
    
    shinyApp(ui = ui, server = server)