我写了一个小小的闪亮应用来测试用户上传数据的变量选择功能。这是我的代码:
ui.R
shinyUI(pageWithSidebar(
headerPanel("CSV Data explorer"),
sidebarPanel(
fileInput('datafile', 'Choose CSV file',
accept=c('text/csv', 'text/comma-separated-values,text/plain')),
htmlOutput("varselect", inline=TRUE),
selectInput("vars", "Select a variable:",choices=htmlOutput("varselect")),
br()
),
mainPanel(
dataTableOutput("table")
)
))
server.R
shinyServer(function(session,input, output) {
Dataset <- reactive({
infile <- input$datafile
if (is.null(infile)) {
return(NULL)
}
read.csv(infile$datapath)
})
observe({
output$varselect <- renderUI({
if (identical(Dataset(), '') || identical(Dataset(),data.frame())) return(NULL)
updateSelectInput(session, inputId="vars", label="Variables to use:",
choices=names(Dataset()), selected=names(Dataset()))
})
})
output$table <- renderDataTable({
if (is.null(input$vars) || length(input$vars)==0) return(NULL)
return(Dataset()[,input$vars,drop=FALSE])
})
})
如果您继续在任何csv文件上进行测试,您将看到2个问题: 1.乱七八糟地显示selectInput()框上方的所有变量名称,这是由代码引起的:
htmlOutput(“varselect”,inline = TRUE)
但是如果我删除这行代码,我的selectInput就会消失。
selectInput(“vars”,“选择变量:”,choices = htmlOutput(“varselect”),multiple = TRUE),
并尝试点击多个选项,它不会反映在主面板的表格中。
我一直在努力解决这个问题。请有人帮帮忙吧!数百万的提前感谢!
此致 明迪
答案 0 :(得分:0)
我认为你让你的过于复杂。简而言之,您只需要uiOutput
代替您的ui.R中的htmlOutput
和selectInput
陈述。似乎也不需要updateSelectInput
或observe
函数。您可以将代码简化为以下内容,并且多项选择似乎可以正常工作:
ui.R
shinyUI(pageWithSidebar(
headerPanel("CSV Data explorer"),
sidebarPanel(
fileInput('datafile', 'Choose CSV file',
accept=c('text/csv', 'text/comma-separated-values,text/plain')),
uiOutput("varselect"),
br()
),
mainPanel(
dataTableOutput("table")
)
))
server.R
shinyServer(function(session,input, output) {
Dataset <- reactive({
infile <- input$datafile
if (is.null(infile)) {
return(NULL)
}
read.csv(infile$datapath)
})
output$varselect <- renderUI({
if (identical(Dataset(), '') || identical(Dataset(),data.frame())) return(NULL)
cols <- names(Dataset())
selectInput("vars", "Select a variable:",choices=cols, selected=cols, multiple=T)
})
output$table <- renderDataTable({
if (is.null(input$vars) || length(input$vars)==0) return(NULL)
return(head(Dataset()[,input$vars,drop=FALSE]))
})
})