【发布时间】:2016-04-04 02:29:51
【问题描述】:
我有一个闪亮的应用程序,它选择 xlsx/csv 文件并将其上传到系统,上传后,我希望将我提取的数据表的列名填充到 selectInput() 或 selectizeInput()。
以下代码表示用户上传数据文件的一个事件
ui.R
library(markdown)
require(XLConnect)
shinyUI(navbarPage(img(class="img-polaroid",
src=paste0("http://www.iconsdb.com/icons/preview/black/stackoverflow-5-xl.png")),
tabPanel("Table",
titlePanel("Select Data"),
sidebarLayout(
sidebarPanel(
selectInput("fileType", "Select File Type:",
c("MS Excel Worksheet (xls,xlsx)" = "xls",
"Text/CSV (.csv)" = "csv"
)
),
fileInput('file1', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'text/tab-separated-values',
'text/plain',
'.csv',
'.tsv',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xlsx',
'.xls'
)
),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',
c(Comma=',',
Semicolon=';',
Tab='\t'),
','),
radioButtons('quote', 'Quote',
c(None='',
'Double Quote'='"',
'Single Quote'="'"),
'"'),
tags$hr()
),
mainPanel(
dataTableOutput('table')
)
)
),
tabPanel("Plot",
sidebarLayout(
sidebarPanel(
radioButtons("plotType", "Plot type",
c("Scatter"="p", "Line"="l")
)
),
mainPanel(
plotOutput("plot")
)
)
),
navbarMenu("More",
tabPanel("Summary",
verbatimTextOutput("summary")
)
)
))
server.R
shinyServer(
function(input, output, session)
{
output$plot <- renderPlot({
plot(data$Count,data$Sales, type=input$plotType)
})
output$summary <- renderPrint({
summary(data)
})
output$table <- renderDataTable({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
if(input$fileType=='csv'){
table1<-read.csv(inFile$datapath, header = input$header,
sep = input$sep, quote = input$quote)
return(table1)
} else if(input$fileType=='xls'){
table1 <- readWorksheetFromFile(inFile$datapath, sheet=1)
}
})
}
)
公平地说,我现在有一个工作输入系统,可以从 Excel 源或文本/CSV 中获取数据。此后,我希望创建一个动态列表,将 colnames(output$table) 的值传递给我的 ui.R 并将其放在指定位置。
我该怎么做?
我尝试使用 Mason DeCamillis 对 How to get vector of options from server.R to ui.R for selectInput in Shiny R App 的回答中的 uiOutput(),但 R 向我抛出“找不到对象”错误。
另外,我想到我必须使用reactive() 才能将数据来回传递到 UI 和服务器。但是不知道该怎么做。
【问题讨论】:
-
This article 对于任何试图理解下面@NicE 的答案,或者一般开始使用 Shiny 中的反应式 UI 的人来说都是一个有用的参考。