Reputation: 762
I upload a file to shiny (csv or excel) and I create an object with the file data. I want this object global because I use the data across different outputs.
My original (simplified) server.R code is:
shinyServer(function(input, output) {
output$contents <- renderTable({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header = input$header, sep = input$sep, quote = input$quote, dec = ".")
data
})
output$grafic <- renderPlot({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header = input$header, sep = input$sep, quote = input$quote, dec = ".")
barplot(table(data$SEVERIDAD), main="Severitat dels riscos detectats")
})
})
So, I have to repeat the code in order to create the object "data" two times.
After read other posts I tried this code but doesn't work:
inFile <- input$file1
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header = input$header, sep = input$sep, quote = input$quote, dec = ".")
shinyServer(function(input, output) {
data <- reactive(data)
output$contents <- renderTable({
data <- data()
data
})
output$grafic <- renderPlot({
data <- data()
barplot(table(data$SEVERIDAD), main="Severitat dels riscos detectats")
})
})
I think that the last code doesn't work because no file can't be uploaded when the application is loaded.
Thanks!
Upvotes: 2
Views: 2118
Reputation: 29387
Create one reactive expression for the data, then use it for all your magic later on ... Note the code hasn't been tested and for local use only (let me know if it works)... For Global implementation you can use <<-
as an assignment operator
shinyServer(function(input, output) {
# Read the file into my_data, storing the data in this variable
my_data <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
data <- read.csv(inFile$datapath, header = input$header, sep = input$sep,quote = input$quote, dec = ".")
data
})
# Create the table
output$contents <- renderTable({
my_data()
})
# Create a plot
output$grafic <- renderPlot({
barplot(table(my_data()$SEVERIDAD), main="Severitat dels riscos detectats")
})
})
Upvotes: 3