I'm new to R-Shiny and my question might be very simple. After hours of thinking and searching, I couldn't solve the issue. Here is the problem:
1) My app asks user to upload his dataset.
2) Then in the server file, I read the dataset and I did some analyses and I report back the results into the user interface.
3)My user interface has 4 different out puts.
4) I read the dataset in the "render" function of each output. ISSUE: by doing so, the data is locally defined in the scope of each function which means that I need to read it over again for each output.
5) This is very in-efficient, Is there any alternative? using reactive ?
6) Below is a sample code showing how I wrote my server.R:
shinyServer(function(input, output) {
# Interactive UI's:
# %Completion
output$myPlot1 <- renderPlot({
inFile <- input$file
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
# I use the data and generate a plot here
})
output$myPlot2 <- renderPlot({
inFile <- input$file
if (is.null(inFile)) return(NULL)
data <- read.csv(inFile$datapath, header = TRUE)
# I use the data and generate a plot here
})
})
How can I just get the input data once and just use the data in my output functions ?
Thanks very much,
Your title asks about importing a data frame into shiny. That can be done by storing the data frame either as a binary file using the save() function or a csv file using write. csv() and having the shiny app read it in using load() for a binary file or read. csv() for a csv file.
Along with Shiny elements, you can use HTML elements to stylize your content in your application. In my opinion, R Shiny is very easy to learn despite how powerful the tool is. If you're working on a side project or looking to add something to your portfolio, I highly recommend trying it out.
The most trivial way to save data from Shiny is to simply save each response as its own file on the current server. To load the data, we simply load all the files in the output directory. In our specific example, we also want to concatenate all of the data files together into one data.
You can call the data from the file in a reactive
function. It can then be accessed for example as
myData()
in other reactive
functions:
library(shiny)
write.csv(data.frame(a = 1:10, b = letters[1:10]), 'test.csv')
runApp(list(ui = 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')
)
)
)
, 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 <- renderTable({
myData()
})
}
)
)
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