首先,使用req 代替if (...) return(NULL),如果input$datafile 为NULL,它将引发一个“静默”异常,它会阻止错误传播。它将简化您的代码,并且使用它是一个非常好的实践。另见validate 和need。
你的问题的答案很简单:
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)