Shiny to output a function that generates a pdf file itself - r

I am trying to use Shiny to build an app with a function that output a pdf file. Specifically, the function I am trying to use is the msaPrettyPrint function from the msa package. It uses the texi2pdf function from the tools package to generate a pdf file.
For example, if you run the following code, you will generate a pdf called "myFirstAlignment.pdf" with an amino acid sequence alignment in your working directory.
# source("http://www.bioconductor.org/biocLite.R")
# biocLite("msa")
library(msa)
mySequenceFile <- system.file("examples", "exampleAA.fasta", package="msa")
mySequences <- readAAStringSet(mySequenceFile)
myFirstAlignment <- msa(mySequences)
msaPrettyPrint(myFirstAlignment, output="pdf", showNames="left",showLogo="top",consensusColor="BlueRed", logoColors="accessible area", askForOverwrite=FALSE)
I was wondering if there is a way to make the following code works? I think the problem might be because the output is already a pdf file. I want to see the pdf output on screen if possible. If not possible to see it on screen, where is the pdf file and if I can download it?
library(shiny)
runApp(list(
#Load the exmaple from the msa package.
mySequenceFile <- system.file("examples", "exampleAA.fasta", package="msa"),
mySequences <- readAAStringSet(mySequenceFile),
myFirstAlignment <- msa(mySequences),
# A simple shiny app.
# Is it possible to see the generated pdf file on screen?
ui = fluidPage(plotOutput('plot')),
server = function(input, output) {
output$plot <- renderPlot(msaPrettyPrint(myFirstAlignment, output="pdf", showNames="left",showLogo="top",consensusColor="BlueRed", logoColors="accessible area", askForOverwrite=FALSE))
}
))
One thing to mention is that this code needs LaTeX to work. You would need LaTeX to run the example.
Thanks a lot!

I was having issues running your example but this should work
library(shiny)
runApp(list(
#Load the exmaple from the msa package.
mySequenceFile <- system.file("examples", "exampleAA.fasta", package="msa"),
mySequences <- readAAStringSet(mySequenceFile),
myFirstAlignment <- msa(mySequences),
# A simple shiny app.
# Is it possible to see the generated pdf file on screen?
ui = fluidPage(downloadButton('downloadPDF')),
server = function(input, output) {
output$downloadPDF = downloadHandler(
filename = 'myreport.pdf',
content = function(file) {
out = msaPrettyPrint(
myFirstAlignment
, file = 'myreport.pdf'
, output="pdf"
, showNames="left"
, showLogo="top"
, consensusColor="BlueRed"
, logoColors="accessible area"
, askForOverwrite=FALSE)
file.rename(out, file) # move pdf to file for downloading
},
contentType = 'application/pdf'
)
}
))

Maybe you can use the msaPrettyPrint file argument to store the pdf locally, and then use this solution displaying a pdf from a local drive in shiny to put a pdf viewer in your application.

Thanks so much for the help from JackStat and Malanche. The following works for downloading the result!
library(shiny)
runApp(list(
#Load the exmaple from the msa package.
mySequenceFile <- system.file("examples", "exampleAA.fasta", package="msa"),
mySequences <- readAAStringSet(mySequenceFile),
myFirstAlignment <- msa(mySequences),
# A simple shiny app.
# Is it possible to see the generated pdf file on screen?
ui = fluidPage(downloadButton('downloadPDF')),
server = function(input, output) {
output$downloadPDF = downloadHandler(
filename = 'myreport.pdf',
content = function(file) {
msaPrettyPrint(
myFirstAlignment
, file = 'myreport.pdf'
, output="pdf"
, showNames="left"
, showLogo="top"
, consensusColor="BlueRed"
, logoColors="accessible area"
, askForOverwrite=FALSE)
file.rename("myreport.pdf", file) # move pdf to file for downloading
},
contentType = 'application/pdf'
)
}
))

Related

Highcharter Shiny bulk command-line rendering and export

I've built an extensive Shiny app which relies heavily on Highcharter for its graphics. Now I'm trying to make a download button that allows the user to download a ZIP file with multiple PDF files, each having a different chart.
I managed to get it to work with ggPlot (hat-tip to Shiny R Zip multiple PDFS for download), but cannot seem to figure it out with Highcharts. I know part of the problem is because Highcharts doesn't output an image, but rather an SVG(? or perhaps JSON?). So I'm stuck on how to convert, within R/Shiny code, the chart to a PDF, since it's not rendered or displayed in the browser.
I tried first to render as SVG, then use rsvg_pdf() (from library rsvg) to convert to PDF, but to render as SVG we need to open a rendering device and close it with dev.off(), which saves the file. I couldn't find a way to capture this in-between and then pass it to rsvg_pdf().
Instead, would the solution lie in invoking the (unix) command-line, and do conversion there? Is there a way to pass a chart to the Highcharts exporting module without it showing up for the end-user?
Thanks a lot for your help!
See below for a reproducible example:
ui.R
library(shiny)
shinyUI(
fluidPage(
headerPanel(title="testing Downloadhandler"),
sidebarLayout(
sidebarPanel(
selectInput("ngear", "Select the gear number", c("Cylinders" = "cyl", "Transmission" = "am", "Gears" = "gear")),
submitButton("Update!"),br(),
),
mainPanel(
tabsetPanel(type="tab",
tabPanel("Plot", plotOutput("plot"),
downloadButton("downloadZippedPlots", "Download Zipped Plot")
)
)
)
)
)
)
Server.R
library(shiny)
library(highcharter)
shinyServer(function(input,output){
mtreact <- reactive({
mtcars[,c("mpg", input$ngear)]
})
output$plot <- renderPlot({
boxplot(mtreact())
})
output$downloadZippedPlots <- downloadHandler(
filename = function(){
paste("mtcars-plots-zipped", "zip", sep=".")
},
content = function(fname){
fs <- c()
tmpdir <- tempdir()
setwd(tempdir())
for (column in c("cyl", "am", "gear")) {
path <- paste(column, "pdf", sep=".")
fs <- c(fs, path)
# --- This works ---
pdf(paste(column, "pdf", sep="."))
boxplot(mtcars[,c("mpg", column)])
dev.off()
# --- This doesn't work ---
hchart(mtcars, "bar", hcaes(x=mpg, y=!!column))
# --- This also doesn't work ---
this_chart <- hchart(mtcars, "bar", hcaes(x=mpg, y=!!column))
print(this_chart)
dev.off()
}
zip(zipfile=fname, files=fs)
},
contentType = "zip"
)
})

Deploying R Markdown File with Shiny Component

Building off my previous question, I'm having trouble creating a DEPLOYABLE R Markdown file that has a Shiny component JUST to allow user to upload an Excel workbook.
Essentially, I want to run Python code on top of the data that the user provides.
This doesn't seem to deploy correctly to RConnect (it just times out):
---
output: html_document
---
library(dplyr)
library(miniUI)
library(shiny)
library(XLConnect)
launch_shiny <- function() {
ui <- miniPage(
gadgetTitleBar("Input Data"),
miniContentPanel(
fileInput(inputId = "my.file", label = NULL,
multiple = FALSE)
)
)
server <- function(input, output, session) {
wb <- reactive({
new.file <- input$my.file
loadWorkbook(
filename = new.file$datapath,
create = FALSE,
password = NULL
)
})
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
df_lst <- reactive({
# read all sheets into a list
lapply(getSheets(wb()),
function(sheet){
readWorksheet(object = wb(),
sheet = sheet)
})
})
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
observeEvent(input$done, {
# get the list of dfs from the app
stopApp(c(df_lst()))
})
}
runGadget(ui, server)
}
test <- launch_shiny()
If I add runtime: shiny at the beginning, it would fail as runGadget uses runApp, which is also used by shiny; however, I need to make sure that I can return a variable (in this case, list of data frames) to the global environment, which is why I was using stopApp.
What are my options at this point?

How to download the edited dataframe in .csv format in rshiny?

I am developing an Rshiny application in which I edited the contents of the dataframe and downloading the edited dataframe in .csv format. But the downloaded file is not in .csv format. Can anyone help me with this issue?
output$downloadData <- downloadHandler(filename = function() {paste(Sys.time(), 'Edited Table.csv', sep='') } ,content = function(file) {write.csv(sample_data(), file, row.names = FALSE)})
This is the code used. Thanks in advance!!
I've tried to replicate your results with an example, but I couldn't reproduce your issue. Here is a self-sufficient RShiny App which downloads a .csv file. Make sure your app follows this template, if the issue still persists please provide a reproducible example of the same.
library(shiny)
ui <- fluidPage(
downloadButton("downloadData", "Download")
)
server <- function(input, output) {
# Your Sample dataset
sample_data <- reactive({mtcars})
output$downloadData <- downloadHandler(
filename = function() {
paste(Sys.time(), ' Edited Table.csv', sep='')
},
content = function(file) {
write.csv(sample_data(), file, row.names = FALSE)
}
)
}
shinyApp(ui, server)

R shiny plot appear either in PDF or in dashboard

I have an R shiny which generates a dashboard with some plots.
I implemented a download button to download the report as a PDF using knitr. Here is part the problematic part of the code:
hist_pl <- reactive({
inFile <- input$file
if (is.null(inFile))
return(NULL)
dataf <- getDF()
h <- hist(dataf)
par(new = T)
plot(x = h$mids, y=ec(h$mids)*max(h$counts), col = rgb(0,0,0,alpha=0), axes=F,xlab=NA, ylab=NA)
})
output$hist1 <- renderPlot({
hist_pl()
})
The problem is as follow:
When I comment the 'renderPlot' part of the code, the histogram appears normally in the PDF report (but not in the dashboard). When I uncomment it, the histogram disappear from the PDF (and appear in the dashboard).
The code for the download button is fairly simple:
output$report = downloadHandler(
filename = 'myreport.pdf',
content = function(file) {
out = knit2pdf('input.Rnw', clean = TRUE)
file.rename(out, file) # move pdf to file for downloading
},
contentType = 'application/pdf'
)
and the input.Rnw file:
\documentclass{article}
\begin{document}
<<names>>=
input$Val1
input$Val2
#
<<>>=
#output$mpgPlot ## N.B. This threw an error! Cannot call an object like this from shiny
print(hist_pl())
#
<<>>=
print(hist_pl())
#
\end{document}
Can someone tell me what could the problem be?

Shiny R - source script that updates data frame - error in .jcall

I am trying to build a shiny application that visualizes data using ggplot2. I want the app to be adaptive to new data that is copied as .xlsx files to a dropbox folder.
I wrote a script to read all excel files in the dropbox folder and to tranform them to a data frame (.Rda). The script works perfectly fine but when I try to source it from my shiny app, the application breaks down. Below you can find my app, the script to import data and the error that occurs.
This is an example of my App:
library(shiny)
library(ggplot2)
load("df.Rda")
ui <- bootstrapPage(
actionButton(inputId = "button", label="Upload new Data"),
plotOutput("plot")
)
server <- function(input, output) {
observeEvent(input$button,{
source("PreparationServer.R")
})
output$plot <- renderPlot(
ggplot(df, aes(City, Total.Inc.VAT))+
geom_bar(stat="identity")
)
}
shinyApp(ui, server)
This is the script I use to transform the excel files to .Rda:
###Load required libraries
library(xlsx)
##########################################################################
## Load Excel Sheets as Data Frames
files <- (Sys.glob("c:///Users/T400/Dropbox/HTM (1)/*.xlsx"))
listOfFiles <- lapply(files, function(x) read.xlsx(x,
sheetIndex = 1,
colIndex = 1:19,
header=TRUE,
encoding = 'UTF-8'))
df <- as.data.frame(listOfFiles[1])
for(i in 2:length(listOfFiles)){
df_temp <- as.data.frame(listOfFiles[i])
df <- rbind(df, df_temp)
}
save(df, file="c://Users/T400/Dropbox/HTM (1)/df.Rda")
##########################################################################
I am getting the following error when I try to source my script from the shiny app:
Warning: Error in .jcall: java.lang.IllegalArgumentException: Your
InputStream was neither an OLE2 stream, nor an OOXML stream

Resources