Include multiple graphics with R-markdown - r

I have an R vector of filepaths for pdf figures I would like to put into my knitr document and knit to html. I see that I can get a single pdf to be included with
knitr::include_graphics(filepaths[1])
My filepaths vector is long and changes size between document compilations. Is there a method of including them all in one go. I had imagined this would work.
for(i in filepaths){knitr::include_graphics(i)}
Had also tried:
for(i in filepaths){ print("![](", filepaths[i], ")" ) }

knitr::include_graphics() is vectorized, so the answer is simply:
knitr::include_graphics(filepaths)
Your first solution does not work because knitr::include_graphics() needs to be the top-level expression. Your second solution does not work because you should use cat() instead of print(), and the chunk option results='asis'.
There are several advantages of using include_graphics() over cat() + results='asis'.

Try using cat instead of include_graphics. For example:
for(i in 1:length(filepaths) {
cat("![](", filepaths[i], ")")
}
This is general Markdown syntax: ![NAME](PATH).
With this solution you will need to use results = "asis" in chunk header.

Related

Can I avoid evaluating inline Rmarkdown `r code` chunks?

In a vignette demonstrating how to use a Suggested package, I have something like this:
if (suggested_package_not_available) {
knitr::opts_chunk$set(eval = FALSE)
}
This means that the vignette still runs etc. although the Suggested package is not available. It just shows the code, not the results.
Can I do something similar for inline R code (`r code`)?
Maybe a hook that uses a regex (a la `r [^`]+`) to add two backticks around the inline code so that the inline code is showed instead of evaluated (which would normally cause an error because the chunks are no longer evaluated)?
A trick might be to print a string or evaluate the expression:
check_code <- function(expr, available){
if(available){
eval(parse(text = expr))
} else {
expr
}
}
check_code("1+1", TRUE)
check_code("1+1", FALSE)
It looks like double backticks before and after as well as breaking the line just after `r will work.
A more thorough explanation at yihui's site: https://yihui.org/knitr/faq/
(#7)
For inline R code, you may use the function knitr::inline_expr() (available in knitr >= v1.8). If you are writing an R Markdown document, you can use a trick: break the line right after `r (no spaces after it), and wrap the whole inline expression in a pair of double backticks, e.g.,
This will show a verbatim inline R expression `r
1+1` in the output.

highlight all inline \Sexpr{} outputs in the generated pdf

I am using knitr for a report wherein I have a lot of inline output text, mostly numeric values, using \Sexpr{}. I want to highlight All these inline outputs in my generated pdf.
Example code:
\documentclass[12pt]{article}
\begin{document}
<<echo=FALSE, include=FALSE>>=
N <- 100 # Total
N_f <- 60 # Women
#
There were \Sexpr{N} people in the company, \Sexpr{N_f} women and \Sexpr{N - N_f} men.
\end{document}
Hence, in the output all the number should be highlighted, i.e. with a shaded background (similar to using with \hl{} with the \usepackage{soul}).
It seems to me that the solution would use one of the inline output hooks. Another possibility might be to write a LaTeX function which search all the \Sexpr{...} expressions in the entire document and highlights them in the generated pdf. I am still learning and can not figure out how to implement these.
Thanks for any help or hints.
Note: The knitr page by yihui talks about manipulation of the numeric value (scientific notation, digits after decimal points) which I have got covered.
The output hook inline can be used to style output from \Sexpr{}. This is as simple as
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", x)})
Just define an arbitrary function that takes an argument x and returns the string to be printed. In this example I used \textbf to make the output bold, but this can be extended to any LaTeX commands.
In this answer, Yihui suggests an improvement that still takes the default inline hook into account. This ensures rounding as usually performed by the default hook:
hook_inline <- knit_hooks$get('inline')
knit_hooks$set(inline = function(x) { sprintf("\\textbf{%s}", hook_inline(x))})

How to layout character value within R chunk

In the knitr package I like the kable function. It gives a nice layout of tables and data frame like objects even as it is called from within an R code chunk. Now I want to do the same thing with a character value. Is there a function that gives a kable-like output ("kprint") that can be formated?
knitr::kable() # exists for tables
knitr::kprint() # does a function like this exists for character values?
This is what I get now:
print("character value") # within the R Chunk
Output in generated report:
## [1] "character value"
And this is what I want, just:
character value
EDIT cat("character value") is not the solution I am looking for because I don't want an R output anymore, but just a plain text.
There are two things to do to get a "raw" character string (without any formatting or additional output like [1]) from R to TEX:
Use the chunk option results = "asis" to instruct knitr not to modify the output.
Use cat instead of print because print adds the lenght of the vector and quotes to the output.
In this context, inline output using \Sexpr{} might be useful because values in \Sexpr{} are by default printed "as they are": \Sexpr{myoutput}.
As there was the question of how to format the output in the comments, here some options:
Add LaTeX to the text you pass to cat: cat("\\emph{foo}"). Don't forget to escape \ by an additional \.
Do the same thing as above, but use a function to do the "dirty work":
makeItNiceR <- function(x) {
return(paste("\\fbox{\\texttt{", x, "}}"))
}
cat(makeItNiceR("foo bar is nice"))
(Note that we could use cat inside makeItNiceR to save some typing, but this makes the function less flexible and we cannot use it in combination with \Sexpr{} anymore.)
Manually add LaTeX formatting commands around \Sexpr{}:
Add formatting to \emph{\Sexpr{myoutput}} directly in LaTeX.
Combine makeItNiceR and \Sexpr{} to get nicely formatted output from \Sexpr{}:
\Sexpr{makeItNiceR(paste(myoutput, "is nice"))}
The following minimal examples demonstrates the usage of all code snippets from above:
\documentclass{article}
\begin{document}
<<results = "asis">>=
makeItNiceR <- function(x) {
return(paste("\\fbox{\\texttt{", x, "}}"))
}
myoutput <- "slim"
cat("foo")
cat("\\emph{foo}")
cat(makeItNiceR("foo bar is nice"))
#
\paragraph{Outside of chunk:} ~\\
\Sexpr{myoutput} \\
Add formatting to \emph{\Sexpr{myoutput}} directly in LaTeX. \\
\Sexpr{makeItNiceR(paste(myoutput, "is nice"))}
\end{document}

R - Handling cut intervals of form [x,y] in tables when converting to LaTeX

I'm working on a document in R, with knitr to pdflatex and am using the extended version of toLatex from memisc.
When I'm producing a table with cut intervals however, the square brackets are not sanitised and the pdflatex job errors because of the existence of [.
I tried putting sanitize=TRUE in the knitr chunk code, but this only works for tikz.
Previously, I have used gsub and replaced the string in the R object itself which is rather inelegant. I'm hoping someone could point me in the direction of a nuance of memisc or knitr that I'm missing or another function/method that would easily handle latex special characters.
Example
library("memisc")
library("Hmisc")
example<-data.frame(cbind(x=1:100,y=1:100))
example$x<-cut2(example$x,m=20)
toLatex(example)
UPDATE
Searching SO I found a post about applying latexTranslate with apply function, but this requires characters so I would have to unclass from factor to character.
I found another SO post that identifies the knitr:::escape_latex function however, the chunk then outputs the stuff as markup instead of translating it (using results='asis') or produces an R style table inside a code block (using results='markup'). I tried configuring it as a hook function in my parent document and it had the effect of outputting all the document contents as markup. This is a brand new area for me so I probably implemented it incorrectly.
<<setup,include=FALSE>>=
hook_inline = knit_hooks$get('inline')
knit_hooks$set(inline = function(x) {
if (is.character(x)) x = knitr:::escape_latex(x)
hook_inline(x)
})
#
...
<<tab-example,echo=FALSE,cache=TRUE,results='asis',sanitize=TRUE,inline=TRUE>>=
library("Hmisc")
library("memisc")
example<-data.frame(cbind(x=1:100,y=1:100))
example$x<-cut2(example$x,m=20)
toLatex(example)
#
According to #yihui this is the wrong way to go
UPDATE 2
I have created a gsub wrapper which will escape percentages etc, however the [ symbol still pushes latex into maths mode and errors.
Courtesy of folks on the tex SE, a [ directly after a line break(\\) is considered an entry into math-mode. It is very simple to prevent this behaviour by adding {} into the output just before a [. My function looks like:
escapedLatex<-function (df = NULL)
{
require("memisc")
gsub(gsub(x = toLatex(df, show.xvar = TRUE), pattern = "%",
replacement = "\\%", fixed = TRUE), pattern = "[", replacement = "{}[",
fixed = TRUE)
}
I'd be very happy to see any alternative, more elegant solutions around and will leave it open for a few days.

Sweave/r - omit initial `>` in code chunks with `echo=true`?

I'm very new to sweave and I feel this will be an easy question, but I'm struggling to solve it myself (googling omit ">" Sweave doesn't really work because I can't search for ">"!).
I'm including a short script into my document:
<<echo=true, results=hide, eval=false>>=
# This is a simple script.
print('Hello World!\n')
#
I basically want the script to appear verbatim in the document, using whatever Sweave's "code" environment is. I don't want to evaluate it - it's just there to demonstrate how one might write a script utilising the functions in the package this document is for.
However, this produces the following in the output document:
> # This is a simple script
> print('Hello World!\n')
Is there some way to omit the > ? Is this the right way to put a script into a Sweave document, or is there some other environment that is meant to be used? (I can use a \begin{verbatim}, but it seemed to me that I should use Sweave commands if possible for code chunks).
I just want the output to be
# This is a simple script.
print('Hello World!\n')
You can try changing the prompt and continue options,
which define the > and + characters.
options(continue=" ", prompt=" ")
I like Vincent's first idea using knitr.
install.packages("knitr")
library(knitr)
Here's a sample Rnw.
\documentclass[a4paper]{article}
%\usepackage{Sweave}
\title{Test case}
\author{romunov}
\begin{document}
\maketitle
<<eval = FALSE, echo = TRUE>>=
# This is a simple script.
print('Hello World!\n')
#
\end{document}
And then
knit("coffee.Rnw")
Convert your .tex file into something pretty, and you get

Resources