I would like to download Report within Shiny App, which includes Plotly graph.
So far i have not found any answer on stackoverflow.
Till this moment im able to download the screenshot of Plotly but it appears only in my working directory and it is not sent to Rmarkdown.
Example code:
library(shiny)
library(plotly)
library(rsvg)
library(ggplot2)
d <- data.frame(X1=rnorm(50,mean=50,sd=10),X2=rnorm(50,mean=5,sd=1.5),Y=rnorm(50,mean=200,sd=25))
ui <-fluidPage(
title = 'Download report',
sidebarLayout(
sidebarPanel(
helpText(),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport'),
tags$script('
document.getElementById("downloadReport").onclick = function() {
var plotly_svg = Plotly.Snapshot.toSVG(
document.querySelectorAll(".plotly")[0]
);
Shiny.onInputChange("plotly_svg", plotly_svg);
};
')
),
mainPanel(
plotlyOutput('regPlot')
)
)
)
server <- function(input, output, session) {
output$regPlot <- renderPlotly({
p <- plot_ly(d, x = d$X1, y = d$X2,mode = "markers")
p
})
observeEvent(input$plotly_svg, priority = 10, {
png_gadget <- tempfile(fileext = ".png")
png_gadget <- "out.png"
print(png_gadget)
rsvg_png(charToRaw(input$plotly_svg), png_gadget)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('testreport.Rmd')
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'testreport.Rmd')
library(rmarkdown)
out <- render('testreport.Rmd', params = list(region = "Test"), switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
shinyApp(ui = ui, server = server)
and testreport.Rmd file:
---
title: "test"
output: pdf_document
params:
name: "Test"
region: 'NULL'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
Any help would be appreciated, because there is not many sources and documentations about R Plotly.
Cheers
If out.png is downloaded to your working directory, you can modify the content function of your downloadHandler to move it to the temporary directory and add it to the report:
content = function(file) {
temp_dir <- tempdir()
tempReport <- file.path(temp_dir, 'testreport.Rmd')
tempImage <- file.path(temp_dir, 'out.png')
file.copy('testreport.Rmd', tempReport, overwrite = TRUE)
file.copy('out.png', tempImage, overwrite = TRUE)
library(rmarkdown)
out <- render(tempReport, params = list(region = "Test"), switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
Your testreport.Rmd could look like (more info here):
---
title: "test"
---
Here's the plot image.
![Plot image](out.png)
You could also pass the arguments of your plotly function in the render of your content function as explained here and use a parametrized Rmarkdown file but this only works for Html reports.
Depending on how deep you want to dive into this, I would suggest creating a .brew file with your shiny code and than you can have your user send the information to the brew file and create the plot. This would give you a static code file which is updated dynamically with new data, each time. The only draw back is that when you make changes to shiny you have to make the same changes to your brew file. The other option is to create a flex dashboard with rmarkdown using the new RStudio 1.0 which becomes a html file.
See (Create parametric R markdown documentation?) for brew example.
Related
I am trying to render a table into a pdf using kable in a markdown document generated from a shiny app. It renders OK until I use any functionality from kableExtra (column_spec in the code below) at which point I get the following error:
! LaTeX Error: Illegal character in array
arg.
The problem seems pretty basic and I'm not the first to have this issue, but other solutions (such as this and this) haven't helped. The table renders OK as HTML but it seems that kableExtra doesn't seem to know that it is rendering latex. If I change the knitr.table.format to "pandoc" it renders but still errors of the column_spec line. Any ideas?
UI.R
fluidPage(
title = 'Download a PDF report',
sidebarLayout(
sidebarPanel(
helpText(),
div("Create a Mark Down Document"),
radioButtons('format', 'Document format', c('PDF', 'HTML'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
plotOutput('regPlot')
)
)
)
Server.R
library(rmarkdown)
library(shiny)
library(magrittr)
library(kableExtra)
function(input, output) {
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html'
))
},
content = function(file) {
src <- normalizePath('report.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd', overwrite = TRUE)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document()
))
file.rename(out, file)
}
)
}
Report.Rmd
Test kable:
```{r}
auto_set_format <- function() {
if (knitr::is_latex_output()) {
options(knitr.table.format = "latex")
} else {
options(knitr.table.format = "html")
}
}
auto_set_format()
tbl <- knitr::kable(mtcars[1:6, 1:6], caption = 'A subset of mtcars.')
# THIS LINE CAUSES THE PROBEM WHEN WRITING TO PDF. COMMENT OUT AND IT WORKS OK
tbl <- tbl %>% column_spec(3, color = "#62BD19")
tbl
```
For column_spec() you need to give an additional Latex package to knitr, i.e. change your report to
---
title: "Example Table"
header-includes:
- \usepackage{dcolumn}
---
Test kable:
```{r}
auto_set_format <- function() {
if (knitr::is_latex_output()) {
options(knitr.table.format = "latex")
} else {
options(knitr.table.format = "html")
}
}
auto_set_format()
tbl <- knitr::kable(mtcars[1:6, 1:6], caption = 'A subset of mtcars.') %>%
column_spec(3, color = "#62BD19")
tbl
```
and you will be able to produce both reports.
I am trying to reproduce an example form the shiny website and running into the following error. There seems to be an issue with .Rmd file. The code seems to save the report.Rmd file in temp directory but somehow it is not reading it when I try to download the plot.
Code
# load required packages
library(shiny)
library(shinydashboard)
library(tidyverse)
ui <- fluidPage(
title = 'Download a PDF report',
sidebarLayout(
sidebarPanel(
helpText(),
selectInput('x', 'Build a regression model of mpg against:',
choices = names(mtcars)[-1]),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
plotOutput('regPlot')
)
)
)
server <- function(input, output) {
regFormula <- reactive({
as.formula(paste('mpg ~', input$x))
})
output$regPlot <- renderPlot({
par(mar = c(4, 4, .1, .1))
plot(regFormula(), data = mtcars, pch = 19)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('report.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd', overwrite = TRUE)
library(rmarkdown)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
shinyApp(ui, server)
Error
Listening on http://127.0.0.1:5552
Warning in normalizePath("report.Rmd") :
path[1]="report.Rmd": No such file or directory
Warning: Error in file.copy: file can not be copied both 'from' and 'to'
[No stack trace available]
Your code confused me a fair bit to be honest with you. I changed some things to get the report to download in my tempdir() successfully so hopefully this answers your question.
content = function(file) {
library(rmarkdown)
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
render(tempReport, switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
}
I had to create report.Rmd file before running the above code. That works like a charm.
I made an R script that allows to get an R Markdown report with a certain type of dataset. Now I would like other people to be able to use this script in order to get an automated report with their data but without using this script (especially for people who don't master R).
I try to go through Shiny hoping to make an interface that loads a dataset and would make my script automatically but I can't make the link between Shiny and my Rmd.
How can I tell my Rmd that the dataset to be processed is not the one that my Rmd script was going to look for in a directory but the one that was loaded on the Shiny interface?
Thanks
Here is the Shiny script with my Rmd called "traitemant_bis.Rmd" :
library(shiny)
library(rmarkdown)
ui <- fluidPage(
titlePanel("Uploading Files"),
sidebarLayout(
sidebarPanel(
fileInput(
inputId = "file1", label = "Choose CSV File",
multiple = FALSE,
accept = c("text/csv", "text/comma-separated-values,text/plain", ".csv")
),
radioButtons("format", "Document format", c("PDF", "HTML", "Word"), inline = TRUE)
),
mainPanel(
tableOutput("contents"),
downloadButton("downloadReport")
)
)
)
server <- function(input, output) {
dataset <- reactive({
req(input$file1)
read.csv(file = input$file1$datapath,
na.strings = ".",
sep = ";",
header = TRUE,
nrows=10)
})
output$contents <- renderTable({
req(dataset())
head(dataset())
})
output$downloadReport <- downloadHandler(
filename = function() {
paste("my-report", sep = ".", switch(
input$format, PDF = "pdf", HTML = "html", Word = "docx"
))
},
content = function(file) {
src <- normalizePath("traitemant_bis.Rmd")
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, "traitemant_bis.Rmd", overwrite = TRUE)
out <- render("traitemant_bis.Rmd", switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
shinyApp(ui, server) ```
I'm giving a simple example showing how you can achieve this. Basically, you can pass any of your data from shiny to Rmd as params.
If you have multiple data frames or any data convert them to a single list and pass as params, you can extract individual data later in the RMarkdown
app.R
library(shiny)
ui <- fluidPage(
# Application title
titlePanel("RMD example"),
downloadButton("btn", "Generate Report")
)
# Define server logic required to draw a histogram
server <- function(input, output) {
data <- reactive({
mtcars
})
output$btn <- downloadHandler(
filename = function(){"myreport.docx"},
content = function(file) {
tempReport <- file.path(tempdir(),"markdown.Rmd")
file.copy("markdown.Rmd", tempReport, overwrite = TRUE)
rmarkdown::render("markdown.Rmd", output_format = "word_document", output_file = file,
params = list(table = data()), # here I'm passing data in params
envir = new.env(parent = globalenv()),clean=F,encoding="utf-8"
)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
Rmd file
---
title: "Untitled"
author: "Mohan"
date: "2/17/2021"
params:
table: [some object]
output: word_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
params$table -> data
data
summary(data)
```
i'm trying to convert a part of my Rshiny in Rmarkdown, but when i try to run this example i get an error, how can i handle it?
this code is part of an example of Rshiny app, but when i try to run something is wrong
or could you help me to find some script to print some tables and graphs from Rshiny into Rmarkdown?
Aserver <-function(input, output) {
regFormula <- reactive({
as.formula(paste('mpg ~', input$x))
})
output$regPlot <- renderPlot({
par(mar = c(4, 4, .1, .1))
plot(regFormula(), data = mtcars, pch = 19)
})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('report.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd', overwrite = TRUE)
library(rmarkdown)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
Aui <- fluidPage(
title = 'Download a PDF report',
sidebarLayout(
sidebarPanel(
helpText(),
selectInput('x', 'Build a regression model of mpg against:',
choices = names(mtcars)[-1]),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
plotOutput('regPlot')
)
)
)
shinyApp(Aui, Aserver)
this is the error
Warning: Error in abs_path: The file 'report.Rmd' does not exist.
[No stack trace available]
Thanks
You should distinghish two paths:
the path where the application is installed/running
the path where you are going to download the result of knitting the Markdown doc
You can get the path where the application is running with getwd().
If you don't explicitly specify a path, the report.Rmd should be located on the same directory as the application so that the application can use it.
Make sure Report.Rmd is in getwd() directory, or specify the path of Report.Rmd :
render(file.path('/custom/directory','report.Rmd'), ...
I need to print a report from a shiny application using r markdown. I have been trying to follow the examples, but after many hours, I need some help.
There are 4 files: app.R, report.Rmd, calculations.R and datos.xlsx
datos.xlsx is an excel file with information to be used by a function defined in calculations.R and used by app.R
app.R is expected to provide the result on the screen and a downloadable report. I do not get the latter and I have been strugling the last two days with this.
Thank you very much!
app.R:
ui <- fluidPage(
titlePanel("Calculations"),
sidebarLayout(
sidebarPanel(
fileInput("file1","Select excel file with data", accept=c("excel",".xlsx",".xls")),
"When are available on the screen, you can download the report",
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
inline = TRUE),
downloadButton('downloadReport')
),
mainPanel(
tableOutput(outputId = "tabla")
)
))
server <- function(input, output) {
source("./calculations.R")
output$tabla<-renderTable({
infile<-input$file1
if(is.null(infile))return(NULL)
calculo(infile$datapath)})
output$downloadReport <- downloadHandler(
filename = function() {
paste('my-report', sep = '.', switch(
input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
))
},
content = function(file) {
src <- normalizePath('report.Rmd')
# temporarily switch to the temp dir, in case you do not have write
# permission to the current working directory
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report.Rmd', overwrite = TRUE)
library(rmarkdown)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
report.Rmd:
title: "Dynamic report"
output: word_document
knitr::opts_chunk$set(echo = FALSE,warning=FALSE,message = FALSE)
Results
print(output$tabla)
calculations.R
library(xlsx)
calculo<-function(archivo){
incrementos_descuentos<-read.xlsx(archivo,sheetName="incrementos - descuentos", check.names = FALSE)
incrementos_descuentos$`Desde / mm`<-as.numeric(as.character(incrementos_descuentos$`Desde / mm`))
incrementos_descuentos$`A / mm`<-as.numeric(as.character(incrementos_descuentos$`A / mm`))
incrementos_descuentos$`Volumen / L`<-as.numeric(as.character(incrementos_descuentos$`Volumen / L`))
incrementos_descuentos$`Resultado L/m`<-as.numeric(as.character(incrementos_descuentos$`Resultado L/m`))
incrementos_descuentos$`Resultado L/m`<-incrementos_descuentos$`Volumen / L`/(incrementos_descuentos$`A / mm`-incrementos_descuentos$`Desde / mm`)
Resutado<-incrementos_descuentos
Resutado
}
It seems that I found the solution, after many days.
I added in app.R a reactive object:
informe <- reactive({
infile<-input$file1
if(is.null(infile))return(NULL)
calculo(infile$datapath)
})
and the I called it from report.Rmd as informe()