no word report creation with R & Shiny (R studio) - r

I created a R shiny application for stats analyses. I'd like that app allowed users to download a word report. I use the code on the shiny website gallery - http://shiny.rstudio.com/gallery/download-knitr-reports.html.
Server
shinyServer(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')
library(rmarkdown)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
})
UI
library(shiny)
shinyUI(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')
)
)
))
It works fine and I can download the report on the web app. I use the proposed code in R studio on a OS X computer and it works fine too. I try to do the same with R studio on a win 7 computer but it doesn't works, the report (html, pdf or docx) is not created whereas the apps works fine.
Can someone help me ?
Ari

Related

Warning in normalizePath("report.Rmd") : path[1]="report.Rmd": No such file or directory

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.

Rmarkdown with Rshiny

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'), ...

how to print a report in shiny using r markdown?

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()

Plotly to pdf report

I'd like to add a plotly plot to a pdf file. This should be done locally (without plotly_IMAGE). Unfortunately I do not have access to webshot (since I do not have the rights to install PhantomJS). Therefore I tried a workaround described here: https://github.com/ropensci/plotly/issues/311 using shiny gadgets. But I wanted to adapt it such that the copying is doen without clicking done in the gadget.
All my attempts (see below) failed because I was not able to delay the downloadHandler until the copying was done.
Any suggestions how the dresired result (copy plotly-Image as png first and use it in pdf-Export afterwards) all done sequentially after click on Download Button?
ui:
library(shiny)
library(plotly)
library(rsvg)
shinyUI(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'),
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:
library(shiny)
library(plotly)
library(rsvg)
shinyServer(function(input, output, session) {
output$regPlot <- renderPlotly({
library(plotly)
set.seed(100)
d <- diamonds[sample(nrow(diamonds), 1000), ]
print("render")
p <- plot_ly(d, x = carat, y = price, text = paste("Clarity: ", clarity),
mode = "markers", color = carat, size = carat)
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')
# 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, '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)
}
)
})

Shiny - not able to download a markdown output

I am really struggling to get this one down. I have searched here and all over but I am not sure what I am doing wrong. I apologize as this maybe a really silly question.But I am a novice.
I have put in place a shiny application, where it renders an existing R markdown file which is compiled based on the Shiny inputs. In the end I get what is like a PDF file. Everything works fine except for the option to download. When I push the download, it just opens another webpage session from the beginning.
How can get the final document displayed as an PDF file downloaded. Really appreciate any help.
I edited this code based on a shiny example, but still cannot get to the bottom of this. When I click on the download button it opens another session.
Edited code
library(shiny)
library(knitr)
shinyServer(function(input, output,session) {
library(knitr)
output$markdown <- renderUI({
HTML(markdown::markdownToHTML(knit('RMarkdown_pdf1.Rmd', quiet = TRUE)))
})
output$downloadData <- 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')
library(rmarkdown)
out <- render('report.Rmd', switch(
input$format,
PDF = pdf_document(), HTML = html_document(), Word = word_document()
))
file.rename(out, file)
}
)
})
library(shiny)
library(knitr)
shinyUI(
fluidPage(
titlePanel("Drift Report - Beta Version 1.0"),
selectInput("n",
"Number of files:",
choices = c(1,2,3,4)),
checkboxInput("d", label = "Data Summary", value = FALSE),
checkboxInput("k", label = "Drift Plots", value = FALSE),
radioButtons("p", label = "Plot Type",
choices = list("Point Plot" = 1, "Cumm Plot"=2, "Both - Side by Side"=3, "Both - One underneath the Other"=4),selected = NULL,inline=TRUE),
sliderInput("s","No of Plots", min = 1, max = 50, value = 10, width = "40%"),
submitButton("Apply Changes"),
conditionalPanel(
condition = "input.n == 1",
fileInput("dat","File Upload for Analysis", accept = ".eff")
),
radioButtons('format', 'Document format for Download', c('PDF', 'HTML', 'Word'),
inline = TRUE),
conditionalPanel(
condition = "input.n == 2",
fileInput("dat","1st File Upload for Analysis"),
fileInput("dat3","2nd File Upload for Analysis")
),
downloadButton('downloadData', 'Download'),
uiOutput('markdown')
)
)
log
2016-04-26T18:50:56.177858+00:00 shinyapps[98254]: Warning in file(filename, "r", encoding = encoding) :
2016-04-26T18:50:56.177862+00:00 shinyapps[98254]: cannot open file 'datEff.R': No such file or directory
2016-04-26T18:50:56.178919+00:00 shinyapps[98254]: Quitting from lines 10-45 (RMarkdown_pdf1.Rmd)
2016-04-26T18:50:56.180088+00:00 shinyapps[98254]:
2016-04-26T18:50:56.182026+00:00 shinyapps[98254]: cannot open the connection
2016-04-26T18:50:56.182763+00:00 shinyapps[98254]: Warning: Error in file: cannot open the connection
2
The id of your download button is downloadData but in server code you used downloadReport. They don't match.

Resources