Generate report from shiny app with markdown : file not found - r

I want to generate a pdf report from my shiny app on shiny server. It work well on my computer.
I try to put in on my shiny server, but when i want to generate the report, I get a firefox "file not found" page instead of getting the pdf.
I use the code shown at : https://shiny.rstudio.com/articles/generating-reports.html
I also try to use directly my .Rmd file instead of copy/paste it to the temp dir, but I got the same error.
My server file :
output$pdfGen <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "rapport_preci.pdf",
content = function(file) {
withProgress(message = "Génération du pdf en cours", value = 0,{
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)
# Set up parameters to pass to Rmd document
params <- list(varSite = input$pdfSite,
...
varTrans= input$valTrans1
)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
out <- render("report.Rmd", output_file = file,
params = params,
encoding = "UTF-8"
)
file.rename(out, file)
})
}
)
I think my app does not found my .Rmd file, but how do I fix that ? All my files are in the same folder.

I just run part of the code, and apparently the problem is when you set owd <- setwd(tempdir())
Here is what that does:
> tempdir()
[1] "/tmp/RtmpKafhlt"
> owd = setwd(tempdir())
> owd
[1] "/home/med"
and you probably don't have access to the home dir of the host server. You need to set replace on.exit(setwd(owd)) with on.exit(owd)

Related

Use R Markdown .docx template in shiny app

I build a shiny app that can filter data and automatically render .docx reports. As I want to customize my reports I would like to use the reference_docx function in the YAML header. I have the shiny app, the markdown document and the template.docx all in one folder. However, the shiny app does not automatically "use" the template.docx as markdown usually does. I assume that I have to load the template in a tempdir() or something like this, but I couldn't quite figure out how. What do I have to do to load the reference docx into the shiny app?
Thank you for your help!
Keep your rmarkdown and word template in app folder.
In your downloadhandler:
output$your_output <- downloadHandler(
filename = function() {
'output_title.docx'
},
content = function(file) {
tempReport <- file.path(temp_folder,
"rmarkdown_template.Rmd")
tempTemplate <- file.path(temp_folder, "template.docx")
file.copy("rmarkdown_template.Rmd", tempReport, overwrite = TRUE)
file.copy("template.docx", tempTemplate, overwrite = TRUE)
# Params
)
rmarkdown::render(tempReport, output_file = file, output_format = 'word_document',
params = params,
envir = new.env(parent = globalenv())
)
}
)
Then in your yaml:
output:
word_document:
reference_docx: template.docx

Unable to see images in rmarkdown table

I am trying to create a downloadable report from a shiny app. The report shows a table in which there are images.
I am passing the table with the url in the table as a parameter to the report as follows:
server <- function(input, output,session) {
data <- reactive({
data <- data.frame(RV3$data[,input$Map_EndoscopistIn],
RV3$data[,input$Map_FindingsIn],
RV3$data[,input$Map_MicroscopicTextIn],
RV3$data$url)
names(data)<-c(input$Map_EndoscopistIn,input$Map_FindingsIn,input$Map_MicroscopicTextIn,"Image")
if(!is.null(input$EndoscopistChooserIn)){
data<-data%>%filter(get(input$Map_EndoscopistIn)==input$EndoscopistChooserIn)
}
data
})
}
output$report <- downloadHandler(
# For PDF output, change this to "report.pdf"
filename = "report.doc",
content = function(file) {
# Copy the report file to a temporary directory before processing it, in
# case we don't have write permissions to the current working dir (which
# can happen when deployed).
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
browser()
# Set up parameters to pass to Rmd document
params <- list(performanceTable=data()
)
# Knit the document, passing in the `params` list, and eval it in a
# child of the global environment (this isolates the code in the document
# from the code in this app).
rmarkdown::render(tempReport, output_file = file,
params = params,
envir = new.env(parent = globalenv())
)
}
)
the url column in data() contains the following path eg:
![](<img src='Images/Images Captured with Proc Data Audit.files/img2527.jpg'>)
The report is as follows:
---
title: "Dynamic report"
always_allow_html: yes
output:
word_document:
fig_caption: true
params:
performanceTable: NA
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
```
```{r,echo=FALSE,warning=FALSE}
pander(params$performanceTable, justify='left',split.table=Inf,caption="Table 1: Cancer diagnoses")
```
The report is in the same folder as the Images folder.
With this I get the following error example:
[pandoc warning] Could not find image `img%20src='Images/Images%20Captured%20with%20Proc%20Data%20Audit.files/img2500.jpg'', skipping...
What am I doing wrong? Is this a reformatting in pander issue or a paths issue or what? Or could this be that the report root is the tmp directory whereas I am referring to images stored in anoter static directory. If it is the latter, what do I do to get paths relative to the temp directory so I can see the images?
The reason you couldn't locate your image file is because you render your report.Rmd from a temp directory where your image doesn't exist:
tempReport <- file.path(tempdir(), "report.Rmd")
file.copy("report.Rmd", tempReport, overwrite = TRUE)
The solution is that the image should also be copied to the same temp directory where markdown syntax ![](img.png) will pick up the file.
As in code change, you should be able to get it working by doing this:
assign a tempDir
tempDir <- tempdir()
Move Rmd as well as images to tempDir
file.copy(c("report.Rmd", "Images/Images Captured with Proc Data
Audit.files/img2527.jpg"), tempDir, overwrite = TRUE)
then render from temp dir
rmarkdown::render(file.path(tempDir, 'report.Rmd'), output_file = file,
params = params,
envir = new.env(parent = globalenv())

R pagedown/shinyapps error - Google Chrome cannot be found

I've been trying to use the pagedown package to create a pdf from a html which is better formatted and more presentable from a shinyapp. It tested fine locally on my machine. After deployment, the document failed to download with the following error from the logs:
Warning: Error in find_chrome: Cannot find Chromium or Google Chrome
[No stack trace available]
I am using Google Chrome to view the app but I am guessing there's more to it than this?
The code for the download is as follows:
output$downloadDrug <- downloadHandler(
filename = function() {("drug-instructions.pdf)},
content = function(file) {
src <- normalizePath('report_drugHTML.Rmd')
src2 <- normalizePath("printout.css")
label <- normalizePath("pxLabel.png")
logo <-normalizePath("logo.png")
fasting <- normalizePath("fasting.png")
owd <- setwd(tempdir())
on.exit(setwd(owd))
file.copy(src, 'report_drugHTML.Rmd', overwrite = TRUE)
file.copy(src2, "printout.css", overwrite = TRUE)
file.copy(label, "pxLabel.png", overwrite = TRUE)
file.copy(logo, "logo.png", overwrite = TRUE)
file.copy(fasting, "fasting.png", overwrite = TRUE)
library(rmarkdown)
out <- render('report_drugHTML.Rmd',
params = list(name = input$px_name, dob = input$dob),
'html_document')
library(pagedown)
out <- pagedown::chrome_print(out, "drug-instructions.pdf")
file.rename(out, file)
}
)
Any suggestions would be greatly appreciated. I am still a novice so please feel free to point out the obvious.

Download files from FTP folder using Loop

I am trying to download all the files inside FTP folder
temp <- tempfile()
destination <- "D:/test"
url <- "ftp://XX.XX.net/"
userpwd <- "USER:Password"
filenames <- getURL(url, userpwd = userpwd,ftp.use.epsv = FALSE,dirlistonly = TRUE)
filenames <- strsplit(filenames, "\r*\n")[[1]]
When I am printing "filenames" I am getting all the file names which are inside the FTP folder - correct output till here
[1] "2018-08-28-00.gz" "2018-08-28-01.gz"
[3] "2018-08-28-02.gz" "2018-08-28-03.gz"
[5] "2018-08-28-04.gz" "2018-08-28-05.gz"
[7] "2018-08-28-08.gz" "2018-08-28-09.gz"
[9] "2018-08-28-10.gz" "2018-08-28-11.gz"
[11] "2018-08-28-12.gz" "2018-08-28-13.gz"
[13] "2018-08-28-14.gz" "2018-08-28-15.gz"
[15] "2018-08-28-16.gz" "2018-08-28-17.gz"
[17] "2018-08-28-18.gz" "2018-08-28-23.gz"
for ( i in filenames ) {
download.file(paste0(url,i), paste0(destination,i), mode="w")
}
I got this error
trying URL 'ftp://XXX.net/2018-08-28-00.gz'
Error in download.file(paste0(url, i), paste0(destination, i), mode = "w") :
cannot open URL 'ftp://XXX.net/2018-08-28-00.gz'
In addition: Warning message:
In download.file(paste0(url, i), paste0(destination, i), mode = "w") :
InternetOpenUrl failed: 'The login request was denied'
I modified the code to
for ( i in filenames )
{
#download.file(paste0(url,i), paste0(destination,i), mode="w")
download.file(getURL(paste(url,filenames[i],sep=""), userpwd =
"USER:PASSWORD"), paste0(destination,i), mode="w")
}
After that, I got this error
Error in function (type, msg, asError = TRUE) : RETR response: 550
Without a minimal, complete, and verifiable example it is a challenge to directly replicate your problem. Assuming the file names don't include the URL, you'll need to combine them to access the files.
download.file() requires a file to be read, an output file, as well as additional flags regarding whether you want a binary download or not.
For example, I have data from Alberto Barradas' Pokémon Stats kaggle.com data set stored on my Github site. To download some of the files to the test subdirectory of my R Working Directory, I can use the following code:
filenames <- c("gen01.csv","gen02.csv","gen03.csv")
fileLocation <- "https://raw.githubusercontent.com/lgreski/pokemonData/master/"
# use ./ for subdirectory of current directory, end with / to work with paste0()
destination <- "./test/"
# note that these are character files, so use mode="w"
for (i in filenames){
download.file(paste0(fileLocation,i),
paste0(destination,i),
mode="w")
}
...and the output:
The paste0() function concatenates text without spaces, which allows the code to generate a fully qualified path name for the url of each source file, as well as the subdirectory where the destination file will be stored.
To illustrate what's happening with paste0() in the for() loop, we can use message() to print to the R console.
> # illustrate what paste0() does
> for (i in filenames){
+ message(paste("Source is: ",paste0(fileLocation,i)))
+ message(paste("Destination is:",paste0(destination,i)))
+ }
Source is: https://raw.githubusercontent.com/lgreski/pokemonData/master/gen01.csv
Destination is: ./test/gen01.csv
Source is: https://raw.githubusercontent.com/lgreski/pokemonData/master/gen02.csv
Destination is: ./test/gen02.csv
Source is: https://raw.githubusercontent.com/lgreski/pokemonData/master/gen03.csv
Destination is: ./test/gen03.csv
>

Running a .Rexec on a .Rmd from command prompt

So I've followed this blog to create an executable file called r2jekyll
Unfortunately, I'm on Windows so I've had to create the .Rexec called r2jekyll differently
the code for r2jekyll is here:
#!/usr/bin/env Rscript
library(knitr)
# Get the filename given as an argument in the shell.
args = commandArgs(TRUE)
filename = args[1]
# Check that it's a .Rmd file.
if(!grepl(".Rmd", filename)) {
stop("You must specify a .Rmd file.")
}
# Knit and place in _posts.
dir = paste0("../_posts/", Sys.Date(), "-")
output = paste0(dir, sub('.Rmd', '.md', filename))
knit(filename, output)
# Copy .png files to the images directory.
fromdir = "{{ site.url }}/images"
todir = "../images"
pics = list.files(fromdir, ".png")
pics = sapply(pics, function(x) paste(fromdir, x, sep="/"))
file.copy(pics, todir)
unlink("{{ site.url }}", recursive = TRUE)
That all works fine, I can run my r2jekyll rexec (thanks to this blog) it runs but nothing happens
I'm up to the last step to run the r2jekyll on a file i've called first_test.Rmd
I run the following code in command prompt
cd (go to directory where my r2jekyll and my first_test.Rmd are sitting)
then
r2jekyll.rexec first_test.Rmd (the blog author used this code, he is on a mac)
and I get the following error
Error: You must specify a .Rmd file.
Execution halted
So my question is: how do I get my r2jekyll.Rexec to do its thing to the first_test.Rmd

Resources