I'm looking to make a shiny app where users upload a text file and can input the terms they want filter (so sentences that have two particular words or phrases). then they can download the results. My script so far looks like:
ui <- fluidPage(
titlePanel("Download data"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose .txt file",
multiple = F,
accept = c(".txt")),
textInput('energy_co', 'Name of energy company'),
textInput('asset', 'name of Asset Manager'),
downloadButton("downloadData", "Download")
),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output, session) {
options(shiny.maxRequestSize=30*1024^2)
output$table <- renderTable({
req(input$file1)
data <- read_lines(input$file1$datapath)
text_df <- as_data_frame(data)
company_data <- text_df %>%
filter(str_detect(terms, input$asset)) %>%
filter(str_detect(terms, input$energy_co)) %>%
distinct(.)
company_data
})
output$downloadData <- downloadHandler(
filename = function() {
paste(company_data, ".csv", sep = "")
},
content = function(file) {
write.csv(company_data, file1, row.names = FALSE)
}
)
}
shinyApp(ui, server)
I can upload the dataset (a .txt file) but nothing happens either when I try and render the table or when I try and download the results as a csv. I think the server script might need to be reactive? any help appreciated
Try this
ui <- fluidPage(
titlePanel("Download data"),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose .txt file",
multiple = F,
accept = c(".txt")),
textInput('energy_co', 'Name of energy company'),
textInput('asset', 'name of Asset Manager'),
downloadButton("downloadData", "Download")
),
mainPanel(
tableOutput("table")
)
)
)
options(shiny.maxRequestSize=30*1024^2)
server <- function(input, output, session) {
company_data <- reactive({
req(input$file1,input$asset,input$energy_co)
data <- read_lines(input$file1$datapath)
text_df <- as_data_frame(data)
company_data <- text_df %>%
filter(str_detect(terms, input$asset)) %>%
filter(str_detect(terms, input$energy_co)) %>%
distinct(.)
company_data
})
output$table <- renderTable({
company_data()
})
output$downloadData <- downloadHandler(
filename = function() {
paste(company_data, ".csv", sep = "")
},
content = function(file) {
write.csv(company_data(), file1, row.names = FALSE)
}
)
}
shinyApp(ui, server)
Related
How do you use the filtered output from datatables in further functions?
I am making a Shiny app where the data is uploaded and filtered by the user with a datatable. I then want to use the filtered data to perform some functions. I give one below (calcs()). I am getting the Error: invalid 'x' type in 'x && y'.
The .csv file is:
Day: 1,2,3
Subject: 1,2,3
Location: 1,1,2
ui.R
shinyUI(fluidPage(theme = shinytheme("spacelab"),
# title and subtitles
titlePanel(
h1(HTML("</b>Test App</b>"),
style="text-align:center")),
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose Input .csv File",
multiple = TRUE,
accept = c("text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
downloadButton("downloadData",
"Download Results (.xlsx)")
),
mainPanel(title = "Raw Data",
DT::dataTableOutput("table"),
)
)
))
server.R
shinyServer <- function(input, output, session) {
datasetInput <- reactive({
if(is.null(input$file1)) return(NULL)
csv_data <- read.csv(input$file1$datapath)
})
output$table = DT::renderDataTable(datasetInput(),
filter = "top",
server = "FALSE")
calcs <- reactive({
remove_pos_baseline <- as.data.frame(input$table_rows_all) %>%
group_by(Location) %>%
mutate(count = first(Subject))
})
data_list <- reactive({
list(
table = calcs(),
patient_results = datasetInput()
)
})
output$downloadData <- downloadHandler(
filename = function() {
paste("Output", datasetInput()$Location[1], "-", Sys.Date(), ".xlsx", sep="")
},
content = function(file) {
write_xlsx(data_list(), path = file)
}
)
}
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)
})
}
The example that I'm working with is the iris data. If the current data contains iris[1:15,], how can I upload a .csv file with more iris data and click a button to combine the uploaded data with the current data and save everything in one dataframe?
Here is what I have so far based on what I've read. I was able to create the fileInput and action button but I think my issue is with the reactive button. I'm not sure how to use it properly to achieve what I need.
library(shiny)
library(DT)
data1<-data.frame(iris[1:15,])
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
numericInput('num','Number of rows',value=10,min=0),
actionButton("update", "Combine Data")),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
output$table <- renderTable({
head(data1,n=input$num)
})
x<-reactive({
req(input$file1)
df_uploaded <- read.csv(input$file1$datapath,
header = input$header,
sep = input$sep,
quote = input$quote,
stringsAsFactors = FALSE)
data2<-data.frame(df_uploaded)
return(data2)
})
merged_data<-eventReactive(input$update,{
datam<-rbind.data.frame(data1,x())
return(datam)
})
# output$table <- renderTable({
# head(merged_data(),n=input$num)})
}
shinyApp(ui, server)
Thanks!
The main issue is that read.csv receiving invalid argument i.e. NULL for header, sep, quote as you don't have input$header, input$sep, input$quote in UI.
library(shiny)
library(DT)
data1<-data.frame(iris[1:15,])
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv")
),
numericInput('num','Number of rows',value=10,min=0),
actionButton("update", "Combine Data")),
mainPanel(
tableOutput("table")
)
)
)
server <- function(input, output) {
# output$table <- renderTable({
# head(data1,n=input$num)
# })
x<-reactive({
req(input$file1)
df_uploaded <- read.csv(input$file1$datapath,
#you don't have these variables in the UI, so they will raise an error
#header = input$header,
#sep = input$sep,
#quote = input$quote,
stringsAsFactors = FALSE)
#No need data2 and return(data2) as read.csv returns data.frame by default
#data2<-data.frame(df_uploaded)
#return(data2)
})
merged_data<-eventReactive(input$update,{
datam<-rbind.data.frame(data1, x())
return(datam)
})
output$table <- renderTable({
head(merged_data(), n=input$num)})
}
shinyApp(ui, server)
I am trying to download a file using downloadHandler with observeEvent shiny but I am not able to download the file,
library(shiny)
load(url("http://s3.amazonaws.com/assets.datacamp.com/production/course_4850/datasets/movies.Rdata"))
ui <- fluidPage(
sidebarLayout(
# Input
sidebarPanel(
# Numeric input for number of rows to show
numericInput(inputId = "n_rows",
label = "How many rows do you want to see?",
value = 10),
# Action button to show
actionButton(inputId = "button",
label = "Show")
),
# Output:
mainPanel(
tableOutput(outputId = "datatable")
)
)
)
server <- function(input, output, session) {
# creating a reactive expression
df <- eventReactive(input$button, {
movies %>% head(input$n_rows)
})
# download a csv everytime when user click on show button
observeEvent(input$button, {
output$button <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(df(), file)
}
)
cat("done downloading file \n")
})
# displays the data on the web in tabular format, data comes from reactive event
output$datatable <- renderTable({
df()
})
}
# Create a Shiny app object
shinyApp(ui = ui, server = server)
I was able to execute above code without any errors, but csv file is not downloading, i want to display the data table and download the displayed data on same button click event , how can i achieve this, Am I missing something, any help would be appreciated
Try this:
library(shiny)
library(dplyr)
load(url("http://s3.amazonaws.com/assets.datacamp.com/production/course_4850/datasets/movies.Rdata"))
ui <- fluidPage(
sidebarLayout(
# Input
sidebarPanel(
# Numeric input for number of rows to show
numericInput(inputId = "n_rows",
label = "How many rows do you want to see?",
value = 10),
# Action button to show
downloadButton('downloadData', 'Download data')
),
# Output:
mainPanel(
tableOutput(outputId = "datatable")
)
)
)
server <- function(input, output, session) {
# Reactive value for selected dataset ----
df <- reactive({
movies %>% head(input$n_rows)
})
output$datatable <- renderTable({
df()
})
output$downloadData <- downloadHandler(
filename = function() {
paste("dataset-", ".csv", sep = "")
},
content = function(file) {
write.csv(df(), file, row.names = FALSE)
})
}
# Create a Shiny app object
shinyApp(ui = ui, server = server)
I am fairly new to Shiny Apps and I wish to download the plots as png/pdf file. After publishing the app online, the downloaded filename is correct but it is an empty file. I applied print function in content for downloadHandler but it doesn seem to work. Can anyone help me out? Thanks
ui.r
library(shiny)
ui <- fluidPage(
titlePanel("My First Shiny Project"),
sidebarLayout(
sidebarPanel(
selectInput("select","Choose a Dataset",
choices = list("trees","pressure"),
selected = "pressure"),
selectInput("format","Choose file format",
choices = list("pdf","png"))
),
mainPanel(
plotOutput("graph")
)
),
downloadButton("download","Download Here")
)
server.r
library(shiny)
server <- function(input,output){
data <- function()({
switch(input$select,
"trees" = trees,
"pressure" = pressure)
})
output$graph <- renderPlot(
plot(data())
)
output$download <- downloadHandler(
filename = function(){
paste("data",input$select,input$format,sep = ".")
},
content = function(file){
if(input$format == "png")
png(file)
if(input$format == "pdf")
pdf(file)
print(plot(data()))
dev.off
}
)
}
It seems that the only issue was that you used dev.off instead of dev.off(), you also do not need the print() statement. A working version of your code is shown below, hope this helps!
library(shiny)
library(ggplot2movies)
library(dplyr)
ui <- fluidPage(
titlePanel("My First Shiny Project"),
sidebarLayout(
sidebarPanel(
selectInput("select","Choose a Dataset",
choices = list("trees","pressure"),
selected = "pressure"),
selectInput("format","Choose file format",
choices = list("pdf","png"))
),
mainPanel(
plotOutput("graph")
)
),
downloadButton("download","Download Here")
)
server <- function(input,output){
data <- function()({
switch(input$select,
"trees" = trees,
"pressure" = pressure)
})
output$graph <- renderPlot(
plot(data())
)
output$download <- downloadHandler(
filename = function(){
paste("data",input$select,input$format,sep = ".")
},
content = function(file){
if(input$format == "png")
png(file)
if(input$format == "pdf")
pdf(file)
plot(data())
dev.off()
}
)
}
shinyApp(ui,server)