rendering markdown files into html in shiny - r

My render function to create the html file from the rmd file is as follows:
createReports <- reactive({
annual <- (some data...)
.....
rmarkdown::render(
input = RMD_FILE,
output_format = "html_document",
output_dir = "outputTest",
quiet = TRUE
)
However, when I run this line, The Rmd file loads fine but I get this error:
Quitting from lines 15-21 (5_Year_Average_Dividend_Growth_Rate.Rmd)
Error in nrow(annual) : object 'annual' not found
However, as you can see, I have defined the variable annual within the same function as the rmarkdown::render. However, when it goes into the function render, it does not recognize that there is a variable called annual. I debugged it and right before it goes into rmarkdown::render, the annual variable does exist. How can I fix this?

What you need is, in the rmarkdown document code chunk section where the variable annual is used, set the chunk to be
```{r annual}
your_code_that_uses_annual_variable
```

Related

Local function not found when knitting to HTML

I saw someone ask a similar question to this but did not have a conclusive answer... I am trying to knit an rmd file to html and am using a function that I wrote in a .R file. I get an error saying the function can not be found etc.
Also just a note that when I run the chunk of code that the function is called for, it works. Just an error when knitting.
This is because you're using the knit button in Rstudio which creates a new session then executes rmarkdown::render, in order to use locally defined function you have to call rmarkdown::render from the console.
Note: that this will block the console until the .Rmd file is rendered.
my.envir <- new.env(parent=baseenv())
local({
f <- function() { ... }
#...
}, my.envir)
# OR source your file directly into my.envir
source("ur.file.R", local = my.envir)
rmarkdown::render(input, # path to the .Rmd file
output_format = "html_document", # output type if not set it'll use the first one found in the yaml header
output_file = NULL, # name of the output file by default it will be the
# name of the .Rmd with the extension changed
clean = TRUE, # set to FALSE if you want to keep intermediary files
envir = my.envir, # this where the magic happens
# if you don't want to modify the global env you can create your own environment and add the function to it
quiet = FALSE # set to TRUE if you want to suppress the output
)
EDIT following #KonardRudolph's comments:
It's better to source your file into the rmd itself, as the main goal of Rmarkdown is reproducible research.
```{r setup, include=FALSE}
.
.
.
source("path/to/file.R")
```

How can I make the output of my function (several ggplot2 graphs) an html file (displaying those graphs)?

I'm writing a personal use package which trains/tests models, and finally runs a myriad of LIME and DALEX explanations on them. I save these as their own ggplot2 objects (say lime_plot_1), and at the end of the function these are all returned to the global environment.
However, what I would like to have happen is that, at the end of the function, not only would I have these graphs in the environment but a small html report would also be rendered - containing all the graphs that were made.
I would like to point out that while I do know I could do this by simply using the function within an Rmarkdown or Rnotebook, I would like to avoid that as I plan on using it as an .R script to streamline the whole process (since I'll be running this with a certain frequency), and from my experience running big chunks in .Rmd tends to crash R.
Ideally, I'd have something like this:
s_plot <- function(...){
1. constructs LIME explanations
2. constructs DALEX explanations
3. saves explanations as ggplot2 objects, and list them under graphs_list
4. render graphs_list as an html file
}
1, 2, and 3 all work but I haven't found a way to tackle 4. that doesn't include doing the whole process in a .Rmd file.
EDIT: Thanks to #Richard Telford's and #Axeman's comments, I figured it out. Below is the function:
s_render <- function(graphs_list = graphs_list, meta = NULL, cacheable = NA){
currentDate <- Sys.Date()
rmd_file <- paste("/path/to/folder",currentDate,"/report.Rmd", sep="")
file.create(rmd_file)
graphs_list <- c(roc_plot, prc_plot, mp_boxplot, vi_plot, corr_plot)
c(Yaml file headers here, just like in a regular .Rmd) %>% write_lines(rmd_file)
rmarkdown::render(rmd_file,
params = list(
output_file = html_document(),
output_dir = rmd_file))}
First, create a simple Rmarkdown file, that takes a parameter. The only objective of this file is to create the report. You can for instance pass a file name:
---
title: "test"
author: "Axeman"
date: "24/06/2019"
output: html_document
params:
file: 'test.RDS'
---
```{r}
plot_list <- readRDS(params$file)
lapply(plot_list, print)
```
I saved this as test.Rmd.
Then in your main script, write the plot list to a temporary file on disk, and pass the file name to your markdown report:
library(ggplot2)
plot_list <- list(
qplot(1:10, 1:10),
qplot(1:10)
)
file <- tempfile()
saveRDS(plot_list, file)
rmarkdown::render('test.Rmd', params = list(file = file))
An .html file with the plots is now on your disk:

Way of executing a selected block of markdown in rstudio (with knitr)

Is there a way to test-out and peek at the output of a selected portion of markdown in RStudio? It seems you either run R code or have to compile the entire RMD page in order to see the output.
This is a Windows-only solution and it uses the clipboard instead of the current selection:
Define the following function:
preview <- function() {
output <- tempfile(fileext = ".html")
input <- tempfile(fileext = ".Rmd")
writeLines(text = readClipboard(), con = input)
rmarkdown::render(input = input, output_file = output)
rstudioapi::viewer(output)
}
Then, copy the markdown you want to preview and run preview(). Note that the output might be different from the output in the final document because
the code is evaluated in the current environment
only the copied markdown is evaluated, meaning that the snippet has no context whatsoever.
A solution without using the clipboard will most likely employ rstudioapi::getActiveDocumentContext(). It boils down to something along the lines of a modified preview function
preview2 <- function() {
code <- rstudioapi::getActiveDocumentContext()$selection
# drop first line
# compile document (as in preview())
# stop execution (THIS is the problem)
}
which could be used by running preview() followed by the markdown to render:
preview2()
The value of pi is `r pi`.
The problem is, I don't see how the execution could be halted after calling preview2() to prevent R from trying to parse The value of …. See this related discussion.

rmarkdown shiny user input in chunk?

I have a shiny app that allows the user to download an HTML file (knitted from a .Rmd file) that includes the code used to run the analysis based on all the user inputs. I am trying to write the base .Rmd file that gets altered when user inputs vary. I am having trouble including user input variables (e.g. input$button1) into R code chunks. Say the user input for input$button1 = "text1".
```{r}
results <- someFun(input$button1)
```
And I'd like to have it knitted like this:
```{r}
results <- someFun('text1')
```
Every time I download the knitted HTML though, I get input$button1 getting written to file. I would also like to be able to produce an .Rmd file that is formatted with this substitution. It seems like knit_expand() might be the key, but I can't seem to relate available examples to my specific problem. Is the proper way to knit_expand() the whole .Rmd file and specify explicitly all the parameters you want subbed in, or is there a more elegant way within the .Rmd file itself? I would prefer a method similar to this, except that instead of using the asis engine, I could use the r one. Any help would be greatly appreciated. Thanks!
Got it. Solution below. Thanks to Yihui for the guidance. The trick was to knit_expand() the whole .Rmd file, then writeLines() to a new one, then render. With hindsight, the whole process makes sense. With hindsight.
For the example, p1 is a character param 'ice cream' and p2 is an integer param 10. There is a user-defined param in ui.R called input$mdType that is used to decide on the format provided for download.
Rmd file:
Some other text.
```{r}
results <- someFun("{{p1}}", {{p2}})
```
in the downloadHandler() within server.R:
content = function(file) {
src <- normalizePath('userReport.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, 'userReport.Rmd')
exp <- knit_expand('userReport.Rmd', p1=input$p1, p2=input$p2)
writeLines(exp, 'userReport2.Rmd')
out <- rmarkdown::render('userReport2.Rmd', switch(input$mdType,
PDF = pdf_document(), HTML = html_document(), Word = word_document()))
}
file.rename(out, file)
}
Resulting userReport2.Rmd before rendering:
```{r}
results <- someFun("ice cream", 10)
```

knitr chunks within .bib file

I am using the LaTeX package problems to create solution sets from a database of problems. The database is structured like a bibliography database, in a .bib file. The whole system works beautifully for regular LaTeX, but now some of my solutions have R code (in knitr chunks) in them.
The default sequence of knitting/TeXing/BibTeXing in RStudio is not working-- the code ends up in the document verbatim, along with mangled versions of the chunk delimiters. So, I need to find the right workflow of steps to ensure that the code makes it through.
This package seems to be very set on having two files, one for the database and one for the .tex/.rnw, so I can't make a working example, but something like this:
\documentclass{article}
\usepackage[solution]{problems}
\Database{
#QUESTION{1.1,
problem = {1.1},
solution = {This solution only uses TeX, like $\bar{x}$. It works fine.}}
#QUESTION{1.2,
problem = {1.2},
solution = {This solution includes code
<<>>=
head(iris)
#
It does not work.
}}}
\begin{document}
Problems for this week were 1.1 and 1.2
\problems{1.1}
\problem{1.2}
\end{document}
You will have to knit the .bib file first and then run LaTeX and BibTeX.
While you usually have a .Rnw file that is knitted to .tex and then let LaTeX tools process the .tex and the .bib file you will have to start with a (let's call it) .Rbib file that is knitted to .bib and then processed by LaTeX.
For simplicity, I give the file I called .Rbib above the name bibliography.Rnw but you can choose any extension you like. I chose .Rnw because the syntax used inside is the same as in .Rnw files.
As dummy entries for the bib-file I use data from verbosus.com and added some knitr code.
The first chunk sets global chunk options to prevent knitr from adding the code of the chunks or any markup to the output file. The next chunk shows how for example the title field could be filled with generated content and the \Sexpr{} part is an example how this could be used to add some dynamic text.
<<setup>>=
library(knitr)
opts_knit$set(
echo = FALSE,
results = "asis"
)
#
article{article,
author = {Peter Adams},
title = {
<<echo=FALSE, results = "asis">>=
cat("The title of the work")
#
},
journal = {"The title of the journal"},
year = 1993,
number = 2,
pages = {201-213},
month = 7,
note = {An optional note},
volume = 4
}
#book{book,
author = {Peter Babington},
title = {\Sexpr{"The title of the work"},
publisher = {The name of the publisher},
year = 1993,
volume = 4,
series = 10,
address = {The address},
edition = 3,
month = 7,
note = {An optional note},
isbn = {3257227892}
}
It is important to have the chunk option results = "asis" and to use cat() instead of print(). Otherwise, there would be unwanted characters in the output.
If this is saved as bibliography.Rnw the following is enough to get a .bib file with the chunks evaluated:
knit(input = "bibliography.Rnw", output = "bibliography.bib")
After that only standard LaTeX compilation remains.

Resources