Uploading data to Shiny for analyses - r

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)

Related

How to modifiy a file in real time using shiny?

I want to create a shiny app that do two things. Frist it has to be able to upload XLS file and after the user can add it some columns (in this case, just the column "Tecnico"), but for the moment I cant be able to do that. Once the user write the value for the column and update the table, the app crashed.
library(shiny)
library(readxl)
runApp(
list(
ui = fluidPage(
titlePanel("Use readxl"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")),textInput("tecnix","Tecnico"),
actionButton("go", "update")),
mainPanel(
tableOutput('my_output_data'))
)
),
server = function(input, output){
data1 <- reactive({
inFile <- input$file1
if (is.null(inFile)){return(NULL)}
isolate({
input$file1
my_data <- read_excel(inFile$datapath)
})
my_data
})
observeEvent(input$go, {
data1()$Técnico <- input$tecnix
})
output$my_output_data <- renderTable({data1()})
}
))
Any ideas?
Thank you so much,
As suggested by #Till using reactiveValues will help solve the problem.
library(shiny)
library(readxl)
runApp(
list(
ui = fluidPage(
titlePanel("Use readxl"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")),textInput("tecnix","Tecnico"),
actionButton("go", "update")),
mainPanel(
tableOutput('my_output_data'))
)
),
server = function(input, output){
rv <- reactiveValues(my_data = NULL)
observeEvent(input$file1, {
req(input$file1$datapath)
rv$my_data <- read_excel(input$file1$datapath)
})
observeEvent(input$go, {
rv$my_data$Techni <- input$tecnix
})
output$my_output_data <- renderTable({rv$my_data})
}
))

R shiny not downloading anything

I am working on a data cleaning app. The app is supposed to take a file from the user clean it, and be able to download the cleaned data. For some reason my app will only download the html of the app and not a csv. Any Help would be awesome. Here is what I have so far.
The interface is asking me to add more details but this is all I got
ui.R
library(shiny)
library(DT)
###Allows up to 60 mgs of data
options(shiny.maxRequestSize = 60*1024^2)
navbarPage(
"Astute App",
tabPanel(
"Clean Data",
fluidRow(
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")),
downloadButton("cleaned_data", label = "Download Data"),
),
tabPanel(
"Time Series Analysis",
fluidPage(
)
),
tabPanel(
"Prediction",
fluidPage(
)
),
collapsible = TRUE
)
The interface is asking me to add more details but this is all I got
server.R
library(shiny)
library(DT)
###Allows up to 60 mgs of data
options(shiny.maxRequestSize = 60*1024^2)
function(input, output, session){
########Reads in uplaoded Data
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)
})
######Clean the data#####
Cleaned_data <- df
download_cleaned_data <- downloadHandler(
filename = Cleaned_data,
content = function(file){
file.copy("data/", file)}
)
###Displays Uploaded data unclean
output$sample_table<- DT::renderDataTable({
df <- df_products_upload()
DT::datatable(df)
})
}
Not sure what else to add
A couple of issues in the downloadHandler section. It should look like this:
output$cleaned_data <- downloadHandler(
filename = "mydata.csv",
content = function(file) {write.csv(df_products_upload(), file)}
)
Here is a minimal working example, showing uploading and downloading a file:
library(shiny)
ui <- fluidPage(
#Select file
fileInput('myfileinput', 'Choose file to upload'),
#Download file
downloadButton("myfiledownload", label = "Download file"),
#Data table of loaded file
tableOutput("mydatatable")
)
server <- function(input, output, session) {
#Create a reactive dataframe to hold our loaded file
df_fileuploaded <- reactive({
#If no file selected set the dataframe to null and exit
if (is.null(input$myfileinput)) return(NULL)
#Load the selected file
return(read.csv(input$myfileinput$datapath))
})
#Download handler
output$myfiledownload <- downloadHandler(
filename = "mydata.csv",
content = function(file) {write.csv(df_fileuploaded(), file)}
)
#Data table
output$mydatatable <- renderTable({
df_fileuploaded()
})
}
shinyApp(ui, server)
Here is your full app with those changes:
ui.r
library(shiny)
library(DT)
###Allows up to 60 mgs of data
options(shiny.maxRequestSize = 60*1024^2)
navbarPage(
"Astute App",
tabPanel(
"Clean Data",
fluidRow(
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")),
downloadButton("cleaned_data", label = "Download Data"),
),
tabPanel(
"Time Series Analysis",
fluidPage(
)
),
tabPanel(
"Prediction",
fluidPage(
)
),
collapsible = TRUE
)
server.r
library(shiny)
library(DT)
###Allows up to 60 mgs of data
options(shiny.maxRequestSize = 60*1024^2)
function(input, output, session){
########Reads in uplaoded Data
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$cleaned_data <- downloadHandler(
filename = "mydata.csv",
content = function(file) {write.csv(df_products_upload(), file)}
)
###Displays Uploaded data unclean
output$sample_table<- DT::renderDataTable({
df <- df_products_upload()
DT::datatable(df)
})
}

how to do dynamic dropdown in shiny from imported data?

In R shiny I have imported the .xlsx file using the below code, I have to select the header attributes to the drop-down and want to do the bar chart using that?? I am new to R can anyone help me??
library(shiny)
library(readxl)
runApp(
list(
ui = fluidPage(
titlePanel("File Upload"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")
)
),
mainPanel(
tableOutput('contents'))
)
),
server = function(input, output){
output$contents <- renderTable({
inFile <- input$file1
if(is.null(inFile))
return(NULL)
file.rename(inFile$datapath,
paste(inFile$datapath, ".xlsx", sep=""))
read_excel(paste(inFile$datapath, ".xlsx", sep=""), 1)
})
}
)
)

Downloading pdf plot using shiny app after reading excel files

As, I am new to shiny apps need some assistance, uploading excel file and generating table output in shiny app works fine, but can't able to download the plot to a pdf format
Here is my code
library(shiny)
library(openxlsx)
library(lattice)
runApp(
list(
ui = fluidPage(
titlePanel("plots"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")),
tags$hr(),
downloadButton('down',"download plot")
),
mainPanel(
tableOutput('contents'),
plotOutput('plot'))
)
),
server = function(input, output){
output$contents <- renderTable({
inFile <- input$file1
if(is.null(inFile))
return(NULL)
else
read.xlsx(inFile$datapath)
})
plotInput <- reactive({
df <- input$file1
xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
})
output$plot <- renderPlot({
print(plotInput())
})
output$down <- downloadHandler(
filename = function(){paste("plot",".pdf",sep=".") },
content = function(file) {
pdf(file)
xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
dev.off()
}
)
}
)
)
The problem was that in some parts of your code you were accessing a dynamic data frame via df() but you had never defined it.
In this kind of problem, it is best to create a reactive data frame, say, df which contains the uploaded data and is passed to other reactive parts of the code via df().
Full example:
library(shiny)
library(openxlsx)
library(lattice)
runApp(
list(
ui = fluidPage(
titlePanel("plots"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose xlsx file',
accept = c(".xlsx")),
tags$hr(),
downloadButton('down',"download plot")
),
mainPanel(
tableOutput('contents'),
plotOutput('plot'))
)
),
server = function(input, output){
df <- reactive({
inFile <- input$file1
req(inFile) # require that inFile is available (is not NULL)
# (a user has uploaded data)
# read.xlsx(inFile$datapath)
head(iris, 10)
})
output$contents <- renderTable({
# access uploaded data via df()
df()
})
plotInput <- reactive({
df <- df()
xyplot(df[,2]~df[,1], df ,xlim=c(0,10),ylim=c(0,100),type = "b")
})
output$plot <- renderPlot({
plotInput()
})
output$down <- downloadHandler(
filename = function(){paste("plot",".pdf",sep=".") },
content = function(file) {
pdf(file)
#xyplot(df[,2]~df[,1],df(),xlim=c(0,10),ylim=c(0,100),type = "b")
# you have to print the plot so that you can open pdf file
print(plotInput())
dev.off()
}
)
}
)
)

How to use a data.frame in server.R to update a select menu in ui.R?

Here is my plan for the website:
I use file upload to read a csv file from my local computer using the following code:
datatable <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote)
})
in my ui.R, I will use a select menu to show all the column names of datatable. I will pick more names, like 2, from here.
According to what column names I pick, I will generate some plots.
So, here are my questions:
How can I get those column names in ui.R from the data.frame generated in server.R?
How can I transfer the picked names in ui.R back to server.R so that I can generate the plots?
I read some examples like http://shiny.rstudio.com/gallery/update-input-demo.html or something about renderUI, but I just do not know how to use them or it they are the right way to do this.
Here is my all code. In server.R:
library(shiny)
options(shiny.maxRequestSize=300*1024^2)
shinyServer(function(input, output) {
datatable <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath, header=input$header, sep=input$sep, quote=input$quote)
})
output$contents <- renderDataTable({
datatable()
}, options = list(orderClasses = TRUE))
output$summary <- renderPrint({
summary(datatable(),20)
aaa <- "afefagfaegar"
list(summary(datatable(),20),aaa)
})
})
Here is the code in ui.R
library(shiny)
shinyUI(navbarPage("",
tabPanel("Data Summary",
fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
width=2,
fileInput('file1', 'Choose CSV File',
accept=c('text/csv','text/comma-separated-values,text/plain','.csv')),
tags$hr(),
checkboxInput('header', 'Header', TRUE),
radioButtons('sep', 'Separator',c(Comma=',',Semicolon=';',Tab='\t'),','),
radioButtons('quote', 'Quote',c(None='','Double Quote'='"','Single Quote'="'"),'"')
),
mainPanel(
tabsetPanel(type = "tabs",
tabPanel("Table", dataTableOutput('contents')),
tabPanel("Summary", verbatimTextOutput("summary"))
)
)
)
)
),
tabPanel("Single factor",
fluidPage(
sidebarLayout(
sidebarPanel(
***#I think I should put something here for the select menu***
),
mainPanel()
)
)
),
tabPanel("Multiple factors")
)
)
I think I figure out how to do this.
In server.R, I put:
output$singlefactor <- renderUI({
selectInput("sfactor", "Feature selection:", names(datatable()))
})
In ui.R, I do like:
uiOutput("singlefactor")
So far, everything is fine.

Resources