I am trying to upload a file to Shiny to crunch it and then view it.
I already was able to create a table with a CSV document, but the output myData can't be used as an input for a boxplot or any other graph.
SERVER
shinyServer(function(input, output, session){
myData <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
data
})
output$contents <- renderTable({
myData()
})
}
UI
library(shiny)
write.csv(data.frame(a = 1:10, b = letters[1:10]), 'test.csv')
shinyUI(fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv'))
),
mainPanel(
tableOutput('contents'),
plotOutput('distPlot')
)
)
)
)
How can I use the data from the file I uploaded out of the function myData?
You should use the functions renderDataTable and dataTableOutput from the DT package for rendering your tables. Your code works fine like this:
library(shiny)
library(DT)
server <- function(input, output, session){
myData <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
data
})
output$contents <- DT::renderDataTable({
DT::datatable(myData())
})
}
write.csv(data.frame(a = 1:10, b = letters[1:10]), 'test.csv')
ui<- shinyUI(fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv'))
),
mainPanel(
DT::dataTableOutput('contents'),
plotOutput('distPlot')
)
)
)
)
shinyApp(ui,server)
Also see the article below:
It is also possible to have an user upload csv's to your Shiny app. The code below shows a small example on how this can be achieved. It also includes a radioButton input so the user can interactively choose the separator to be used.
library(shiny)
library(DT)
# Define UI
ui <- shinyUI(fluidPage(
fileInput('target_upload', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'.csv'
)),
radioButtons("separator","Separator: ",choices = c(";",",",":"), selected=";",inline=TRUE),
DT::dataTableOutput("sample_table")
)
)
# Define server logic
server <- shinyServer(function(input, output) {
df_products_upload <- reactive({
inFile <- input$target_upload
if (is.null(inFile))
return(NULL)
df <- read.csv(inFile$datapath, header = TRUE,sep = input$separator)
return(df)
})
output$sample_table<- DT::renderDataTable({
df <- df_products_upload()
DT::datatable(df)
})
}
)
# Run the application
shinyApp(ui = ui, server = server)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With