How do I insert a variable image file in a rmarkdown pdf - r

The problem is simple - How do I insert a variable filename into an rmarkdown PDF? I want to do this:
---
FNL = "image.png"
---
![Some Text](params$FNL)
only I need to pass in the value for FNL when calling rmarkdown::render
The purpose is to give the image a unique ID so that users get images marked for their session.
Anyone able to help with this?

Just use inline R evaluation (works for both HTML and PDF output):
---
title: "Example"
author: "Martin"
date: "March, 11 2017"
output: html_document
params:
img: NULL
---
`r sprintf("![A good boy](%s)", params$img)`
Then you can render the document with the image file by calling
rmarkdown::render("MyDocument.Rmd", params = list(img = "unnamed.png")).

Related

How can I change the placement of the caption and modify the color of cross-referencing in the R markdown generated pdf document?

---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
extra_dependencies: ["float"]
number_sections: false
toc: false
---
```{r, echo = FALSE}
library(ggplot2)
data(mtcars)
names(mtcars)
```
### Heading 1
```{r figure-1,echo=FALSE, fig.cap = "Sample Graph 1"}
ggplot(mtcars,aes(x=mpg,y=hp))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \#ref(fig:figure-2)
\newpage
### Heading 2
```{r figure-2,echo=FALSE, fig.cap = "Sample Graph 2"}
ggplot(mtcars,aes(x=mpg,y=carb))+
geom_point()+
theme_classic()
```
To see another graph, please see figure \#ref(fig:figure-1)
I have tried to enclose #ref in the \textcolor{}{}, but Latex removes the cross-referencing and only shows #ref(fig:figure-1) in the knitted pdf document.
Moreover, I want to put the caption at the top of the figure instead of being at the bottom. I looked over Stackoverflow and users are recommending to use floatrow package to control the placement of caption, but I can't use floatrow with float package. I am using float package in my document to control for extra spaces in my document by using the following code written in Latex:
\usepackage{float}
\let\origfigure\figure
\let\endorigfigure\endfigure
\renewenvironment{figure}[1][2] {
\expandafter\origfigure\expandafter[H]
} {
\endorigfigure
}
Please help me out in sorting out these issues :)
I was able to figure out the solution to both of the problems mentioned in my question. I am sharing my solution to both problems for the other learners below:
Change the Cross-Reference Color
We cannot use Latex \textcolor{}{} to change the color of the cross-referencing in R Markdown. My thinking is R Markdown confuses multiple Latex commands with simple words while knitting the document.
Xie et al. (2020) has addressed this problem by creating a lua filter. I opened "The Notepad" and copied the code given in the book. And I saved the file as color-text.lua. The code is given below for the reader's convenience:
Span = function(el)
color = el.attributes['color']
-- if no color attribute, return unchange
if color == nil then return el end
-- transform to <span style="color: red;"></span>
if FORMAT:match 'html' then
-- remove color attributes
el.attributes['color'] = nil
-- use style attribute instead
el.attributes['style'] = 'color: ' .. color .. ';'
-- return full span element
return el
elseif FORMAT:match 'latex' then
-- remove color attributes
el.attributes['color'] = nil
-- encapsulate in latex code
table.insert(
el.content, 1,
pandoc.RawInline('latex', '\\textcolor{'..color..'}{')
)
table.insert(
el.content,
pandoc.RawInline('latex', '}')
)
-- returns only span content
return el.content
else
-- for other format return unchanged
return el
end
end
Once the file is saved, we need to incorporate color-text.lua in the YAML header of our required document. We will incorporate the lua file by modifying YAML header:
---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
pandoc_args: ["--lua-filter=color-text.lua"]
number_sections: false
toc: false
---
After modifying the YAML header, we can change the font color of cross-referenced text by doing it the following way:
To see another graph, please see figure [\#ref(fig:figure-2)]{color="blue"}
We need to write the cross-referenced text within square brackets followed by color argument within {}.
Changing the placement of the caption and controlling for extra whitespaces
If we want to change the placement of the caption and control for extra white space in our pdf document, we need to include the following lines in our .tex file
\usepackage{floatrow}
\usepackage[onehalfspacing]{setspace}
\floatsetup[figure]{capposition=top}
\floatplacement{figure}{H}
After saving the above tex file as caption_control.tex, we will include it in our YAML header:
---
title: "Annual Report"
author: "Xyz"
date: "`r format(Sys.time(),'%d %B, %Y')`"
output:
bookdown::pdf_document2:
pandoc_args: ["--lua-filter=color-text.lua"]
number_sections: false
toc: false
includes:
in_header: caption.control.tex
---

knitr::is_word_output() to check if the current output type is word – just like knitr::is_latex_output() and knitr::is_html_output()

knitr::is_latex_output() and knitr::is_html_output() allow checking if the current output type LaTex or HTML respectively.
Is there an equivalent for Word as an output format?
If not, what would be the most simple to use workaround?
---
title: "MWE for different file formats in namespace:knitr"
output:
pdf_document: default
html_document: default
word_document: default
---
```{r}
if (knitr::is_html_output()) {
cat("HTML")
}
if (knitr::is_latex_output()) {
cat("LATEX")
}
if (knitr::is_word_output()) {
cat("WORD")
}
## Error: 'is_word_output' is not an exported object from 'namespace:knitr'
```
As of knitr 1.31 (released in January 2021), you can use knitr::pandoc_to() in either of the following ways:
```{r}
if (knitr::pandoc_to("docx")) {
cat("Word")
}
```
```{r, include=knitr::pandoc_to("docx")}
cat("Word")
```
To conditionally output literal text content (rather than R code), it's easiest to use an asis chunk (note that we need to use the echo option instead of include):
```{asis, echo=knitr::pandoc_to("docx")}
This will only appear in Word documents.
```
```{asis, echo=knitr::pandoc_to("docx", "pdf")}
This will be appear in Word and PDF documents.
```
Historical answer
In earlier versions of knitr, you can use an internal knitr function to get the type you want:
is_word_output <- function(fmt = knitr:::pandoc_to()) {
length(fmt) == 1 && fmt == "docx"
}

kable_as_image knitr/kableextra rmarkdown

I am trying to use the function kable_as_image, which from my understanding will save the table as a image. My results though is not a table, dont know if I am doing something wrong as I cant find an example.
---
title: "Untitled"
author: "Test"
date: '2017-11-29'
output: pdf_document
---
```{r}
library(knitr)
library(kableExtra)
```
```{r}
kable_as_image(kable(head(iris)), filename = "~/Documents/.../.../pic")
```
#warning: kpathsea: gloss-$mainlang$.ldf: Unrecognized variable construct `$.'.
What my "picture" looks like:
Now I feel like kable_as_image is a somehow misleading name for the function. As explained in the doc, as least right now, it only works for latex tables, try kable_as_image(kable(..., format = "latex", booktabs = T), filename = "pic").

Passing function in rmarkdown parameter to render plots in html report

I am passing plots generated from shiny to rmarkdown to generate html report. The trouble is wordcloud and pie chart are being accepted in params in rmarkdown document.
Question : How to pass wordcloud and pie plots in rendered html via shiny ?
abc.Rmd
title: "Report using R Markdown"
subtitle: "ABC "
author: "Author name"
output:
prettydoc::html_pretty:
theme: architect
params:
wc : 'NULL'
table: 'NULL'
pie: 'NULL'
app.R(snippet)
rmarkdown::render(input = "report.Rmd",
output_file = "report.html",
params = list(wc=getWordcloud(),
table=getTab(),
pie=getPie()))
Note : getWordcloud(),getTab(),getPie() function are returning plots perfectly in shiny app.
You can't have as a parameter type a function.
See here in parameter type:
http://rmarkdown.rstudio.com/developer_parameterized_reports.html
All of the standard R types that can be parsed by the yaml::yaml.load function are supported including character, integer, numeric, and logical.
I strongly recommend to find a way to make your code working without the need to pass a function in the parameter. Maybe you can pass options of the function and include the function in the rmd?
But, there is ways to bypass that:
One is to use in the parameter the name of the function as a string and to use eval() to evaluate the string as code.
abc.Rmd
title: "Report using R Markdown"
subtitle: "ABC "
author: "Author name"
output:
prettydoc::html_pretty:
theme: architect
params:
wc : wc_function
table: table_function
pie: pie_function
eval(paste0(param$wc_function, "(", my_options_as_string, ")"))
app.R(snippet)
rmarkdown::render(input = "report.Rmd",
output_file = "report.html",
params = list(wc="getWordcloud",
table="getTab",
pie="getPie"))
Another one is to have another r script with the functions, called in the rmarkdown with source.
That way, you can pass the path of the file as a parameter and it allows you to get access to your function inside the rmarkdown (but it implies the name of the functions are fixed)

Dynamically change knitr .Rmd report text

I would like to dynamically change the text of an R markdown report template I'm using depending on certain inputs. I'm calling knitr from the PowerShell.
This is the input I would like to insert into the R markdown text Input:
{
"start": "1/21/2015",
"end": "1/23/2015",
"species: ["RBHS", "DBHS", "CBHS"]
}
.Rmd file
---
title: "Capture Report"
author: "Mitchell Gritts"
date: Sys.Date()
output: html_document
---
```{r load packages, include = FALSE}
LoadScripts()
```
## Capture Table
All SPECIESLIST captured between STARTDATE and ENDDATE are included
in the table. Data included in the table are Species, NDOW ID, Sex, Age,
Marks and Collar information.
SPECIESLIST, STARTDATE and ENDDATE are to be replaced with the values from the input.
Is there a way to do this with knitr or sweave. Or do I use search and replace functions to do this?

Resources