Reputation: 35
I want to create a shiny app where one can upload a csv file and then select columns of that file. The problem is that after uploading a file, my code fails to update the column names for possible choices. Here is a reproducible example. Thank you!
ui <- fluidPage(
fileInput("file1",
"Please choose a csv File",
multiple = FALSE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")),
div(style="display:inline-block", selectInput('var',
'Select the first var',
"") )
)
server <- function( input, output, session ) {
data <- reactive({
inFile <- input$file1
req(inFile)
validate(need(ext == "csv", "Please upload a csv file"))
df = read.csv(inFile$datapath,
header = input$header,
sep = input$sep,
quote = input$quote)
colnames <- names(df)
df
})
output$contents <- renderTable( {
updateSelectInput(session,
inputId = 'var',
label = 'Select the first var',
choices = colnames)
} ) }
shinyApp(ui = ui, server = server)
Upvotes: 1
Views: 966
Reputation: 1513
Some of your reactive expression aren't right, lets split things out to make it easier to follow. In particular use observeEvent
to watch the file input.
library(shiny)
ui <- fluidPage(
fileInput("myfileinput", "Please choose a csv File", multiple = FALSE, accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv")),
selectInput('myselectinput','Select the first var', ""),
tableOutput('mytable')
)
server <- function(input, output, session) {
#Reactive to store loaded data
reactives <- reactiveValues(
mydata = NULL
)
#Observe file being selected
observeEvent(input$myfileinput, {
#Store loaded data in reactive
reactives$mydata <- read.csv(file = input$myfileinput$datapath)
#Update select input
updateSelectInput(session, inputId = 'myselectinput', label = 'Select the first var', choices = colnames(reactives$mydata))
})
#Data table
output$mytable <- renderTable({
reactives$mydata
})
}
shinyApp(ui = ui, server = server)
Upvotes: 1