【问题标题】:r shiny create a dropdown from a column of data in csvr shiny 从 csv 中的一列数据创建一个下拉列表
【发布时间】:2016-08-22 20:42:47
【问题描述】:

我的下拉菜单现在正在填充列名。相反,我想创建一个下拉列表,它只使用第一列中的所有内容作为选项。谁能帮助我的 output$toCol 函数?

服务器.R:

filedata <- reactive({
  infile <- input$datafile
  if (is.null(infile)) {
  # User has not uploaded a file yet
   return(NULL)
  }
  read.csv(infile$datapath, header = TRUE)
})

output$toCol <- renderUI({
  df <-filedata()
  if (is.null(df)) return(NULL)

  items=names(df)
  names(items)=items
  selectInput("species-dropdown", "Species:",items)
})

ui.R

fileInput('datafile', 'Choose CSV file', accept=c('text/csv', 'text/comma-separated-values,text/plain')),
uiOutput("toCol")

【问题讨论】:

    标签: r csv shiny


    【解决方案1】:

    首先,使用req 代替if (...) return(NULL),如果input$datafile 为NULL,它将引发一个“静默”异常,它会阻止错误传播。它将简化您的代码,并且使用它是一个非常好的实践。另见validateneed

    你的问题的答案很简单:

        df <- filedata()
        # as.character: to get names of levels and not a numbers as choices in case of factors
        items <- as.character(df[[1]])
        selectInput("species-dropdown", "Species:", items)
    

    我还添加了small interface 用于上传文件。


    完整示例:

    library(shiny)
    rm(ui)
    rm(server)
    
    server <- function(input, output) { 
    
      filedata <- reactive({
        infile <- input$datafile
        # require that infile is not NULL (?req)
        # it will prevent propagating errors 
        req(infile) 
    
        # read.csv(infile$datapath, header = TRUE)
        iris
      })
    
      output$toCol <- renderUI({
        df <- filedata()
    
        # as.character: to get names of levels and not a numbers as choices in case of factors
        items <- as.character(df[[1]])
    
        selectInput("species-dropdown", "Species:", items)
      })
    
    }
    
    ui <- fluidPage(
      # http://shiny.rstudio.com/gallery/file-upload.html
      sidebarLayout(
        sidebarPanel(
          fileInput('datafile', 'Choose CSV File',
                    accept=c('text/csv', 
                             'text/comma-separated-values,text/plain', 
                             '.csv')),
          tags$hr(),
          checkboxInput('header', 'Header', TRUE),
          radioButtons('sep', 'Separator',
                       c(Comma=',',
                         Semicolon=';',
                         Tab='\t'),
                       ','),
          radioButtons('quote', 'Quote',
                       c(None='',
                         'Double Quote'='"',
                         'Single Quote'="'"),
                       '"')
        ),
        mainPanel(
          uiOutput("toCol")
        )
      )
    )
    
    shinyApp(ui, server)
    

    【讨论】:

    • 这太棒了,非常感谢!我对闪亮真的很陌生,所以我显然还不精通最佳实践。或者写简单的代码
    • 你应该看看these 的文章,尤其是Best practices 部分:) 这是最好的起点(在官方教程之后):)
    猜你喜欢
    • 2018-01-18
    • 2023-02-23
    • 1970-01-01
    • 1970-01-01
    • 2019-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多