I am trying to build simple csv upload example in Shiny. Upload csv file, store header in Select Input control and display each column in table output. As soon as I upload any csv file it shows me below error
Error in [.data.frame: undefined columns selected
However if the same csv file is uploaded again it doesn't show the error.
library(shiny)
library(shinyjs)
ui <- pageWithSidebar(
headerPanel("CSV Upload test"),
sidebarPanel(
fileInput("datafile", h5("Choose CSV file:"),
accept=c('text/csv', 'text/comma-separated-values,text/plain')),
htmlOutput("varselect", inline=TRUE),
selectInput("vars", label = h5("Select a variable:"), choice=NULL, selected = NULL,
multiple=FALSE, selectize=TRUE),
actionButton("unselect", label="Clear All"),
br()
),
mainPanel(dataTableOutput("table")))
server <- function(session,input, output) {
Dataset <- reactive({
infile <- input$datafile
if (is.null(infile)) {
return(NULL)
}
read.csv(infile$datapath)
})
observe({
if (identical(Dataset(), '') || identical(Dataset(),data.frame()))
return(NULL)
updateSelectInput(session, inputId="vars",
choices=names(Dataset()), selected=NULL)
})
observe({
if (input$unselect > 0) {
if (identical(Dataset(), '') || identical(Dataset(),data.frame()))
return(NULL)
updateSelectInput(session, inputId="vars",
choices=names(Dataset()), selected=NULL)
}
})
output$table <- renderDataTable({
if (is.null(input$vars) || length(input$vars)==0) return(NULL)
validate(need(Dataset(), "Awaiting data"))
return(Dataset()[,input$vars,drop=FALSE])
})
}
shinyApp(ui, server)
Also in the selectInput function if I channge option for multiple = TRUE this error at the beginning of csv upload doesn't show.
selectInput("vars", label = h5("Select a variable:"), choice=NULL, selected = NULL,
multiple=FALSE, selectize=TRUE)
Appreciate if someone can help to make me understand what is going on here. Any work around?
shiny
&shinyjs
you're using. – kostr