我的下拉菜单现在填充了列名。相反,我想创建一个简单地使用第一列中的所有内容作为选项的下拉列表。任何人都可以帮我输出$ toCol函数吗?
server.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")
答案 0 :(得分:2)
首先,代替if (...) return(NULL)
使用req
,如果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)