Reputation: 798
I'm trying to upload either a csv file or an rds file and use it as the dataset for creating a table. I tried using a conditional if/else
, but I'm getting this error: argument is of length zero
. I would like to upload it outside of the renderTable as I like to use the reactive dataset for other purposes too.
Code
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file_csv", "Choose CSV File", accept = ".csv"),
checkboxInput("header", "Header", TRUE),
fileInput("file_rds", "Choose RDS File", accept = ".rds"),
),
mainPanel(
tableOutput("table1")
)
)
)
server <- function(input, output) {
dataset <- reactive({
if(input$file_csv) {
file <- input$file_csv
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
read.csv(file$datapath, header = input$header)
} else {
readRDS(file_rds$datapath)
}
})
output$table1 <- renderTable({
head(dataset())
})
}
shinyApp(ui = ui, server = server)
Attempt with observeEvent
(not working):
output$table1 <- renderTable({
req(dataset())
head(dataset())
})
observeEvent(input$file_csv, {
dataset <- read.csv(input$file_csv$datapath, header = input$header)
})
observeEvent(input$file_rds, {
dataset <- readRDS(input$file_rds$datapath)
})
Attempt at rds file (not working):
if(!is.null(input$file_rds )) {
file <- input$file_rds
req(file)
readRDS(file$datapath)
}
Upvotes: 1
Views: 158
Reputation: 886938
We can use
server <- function(input, output) {
dataset <- reactive({
req(input$file_csv)
if(!is.null(input$file_csv )) {
file <- input$file_csv
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "csv", "Please upload a csv file"))
read.csv(file$datapath, header = input$header)
} else {
readRDS(input$file_rds$datapath)
}
})
output$table1 <- renderTable({
head(dataset())
})
}
-validation check
Upvotes: 2