How to render latex code in a string from an rmarkdown code chunk? - r

In R, using an ordinary rmarkdown code chunk (ordinary here means opposite of inline code), how to render some latex code?
Here's an illustrative example:
---
title: "beta test"
output:
html_document
---
```{r}
a = 42
b = "$\\beta$"
c = "$a + 2$"
d = "a + 2"
a
b
c
d
```
`r a`
`r b`
`r c`
`r d`
that generates:
I would like to render the latex code, e.g., the $\\beta$ as it is in the case of the inline code.
My ultimate goal is to generate rendered latex code programmatically from "triple backticks" code chunks.

That's Mathjax code rather than LaTeX. output:html_document indicates that you're producing a html doc.
Anyway, you may try results="asis" and use just one backslash \beta. However, this seems not to be compatible anymore with inline code; a workaround would be to use two variables.
---
title: "beta test"
output:
html_document
---
```{r, results='asis'}
a = 42
b = "$\\beta$"
b1 = "$\beta$"
c = "$a + 2$"
d = "a + 2"
a
b
b1
c
d
```
`r a`
`r b`
`r b1`
`r c`
`r d`
Produces
The inline code

Related

newline or line breaks in rnotebook inline chunks

How to make newlines in inline chunks ? Rendering a word document
---
title: "R Notebook"
output: word_document
---
Cat `r cat("not \n working")`
writeLines `r writeLines("not \n working")`
print `r print("not \n working")`
capture.output + cat `r capture.output(cat("not \n working"))`
```{r results='asis'}
cat("not \n working")
```
EDIT Solution based on shafee and gaut's answers uses triple escape character \
---
title: "R Notebook"
output: word_document
---
Text `r "Simple \\\n is \\\n better"`
We can use:
```{r results='asis'}
cat(paste("it is", "\\\n", "working"))
```
You can use combine_words from {knitr} to do this in inline code.
`r knitr::combine_words(c("it is", "working"), sep = "\\\n", and = "")`

R/exams appears not returning the right solution of an exam

I have the following question:
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, include = FALSE}
correct <- c(
"A (correct)
\\vspace{1cm}
$$\\int f\\left(x\\right) dx$$
",
"B (correct)",
"C (correct)"
)
correct <- sample(correct, 2)
incorrect <- c(
"D (incorrect)",
"E (incorrect)",
"F (incorrect)",
"G (incorrect)",
"H (incorrect)",
"I (incorrect)"
)
incorrect <- sample(incorrect, 6)
```
Question
========
Select from the followings items.
\begin{answerlist}
\item `r correct[1]`
\item `r correct[2]`
\item `r incorrect[1]`
\item `r incorrect[2]`
\item `r incorrect[3]`
\item `r incorrect[4]`
\item `r incorrect[5]`
\item `r incorrect[6]`
\end{answerlist}
Meta-information
================
exname: My question
extype: mchoice
exsolution: 11000000
exshuffle: TRUE
And I use the following code to generate the exam:
library(exams)
myexam <- list(
"question.Rmd",
"question.Rmd",
"question.Rmd",
"question.Rmd"
)
exm <- exams2pdf(myexam,dir = "/tmp/", template = "x.tex")
exm[[1]][[1]]$metainfo$solution
where my template is:
\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[portuges]{babel}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{longtable}
\usepackage{multicol}
\usepackage{enumitem}
\setlength{\parindent}{0em}
\setlength{\parskip}{\bigskipamount}
\pagestyle{fancy}
\setlength\headheight{55pt}
\fancyhf{} % sets both header and footer to nothing
\renewcommand{\headrulewidth}{0pt}
\newenvironment{answerlist}%
{\renewcommand{\labelenumii}{(\alph{enumii})}\begin{multicols}{4}\begin{enumerate}}%
{\end{enumerate}\end{multicols}}
\newenvironment{question}{\item }{}
%\setkeys{Gin}{keepaspectratio}
\begin{document}
This is my exam!
Part 1
\begin{enumerate}
%% \exinput{exercises}
\end{enumerate}
Part 2
\begin{enumerate}[resume]
\input{exercise4}
\end{enumerate}
\end{document}
However, the solution for my question 1 in the exam is not correct (exm[[1]][[1]]$metainfo$solution). Is this a bug? Or am I doing something wrong?
However, the solution for my question 1 in the exam is not correct (exm[[1]][[1]]$metainfo$solution). Is this a bug? Or am I doing something wrong?
(Sorry for repeating the last paragraphs, but otherwise Stackoverflow would not allow me to post -- it complains about too much code.)
The problem is that you use a LaTeX-style {answerlist} environment in a Markdown exercise. Hence the answer list is not processed correctly internally but it is still rendered but only when doing so via LaTeX (as you do in exams2pdf()). If you use exams2html("question.Rmd") you see that the answer list is not shown. Unfortunately, no error is thrown, I will check whether this can be improved.
To fix the issue you need to use a Markdown-style question list, either "by hand"
Answerlist
----------
* `r correct[1]`
* `r correct[2]`
* `r incorrect[1]`
* `r incorrect[2]`
* `r incorrect[3]`
* `r incorrect[4]`
* `r incorrect[5]`
* `r incorrect[6]`
or via the answerlist() function (as already shown in: Questions with a fixed and pre-specified number of true and false answers).
```{r, echo = FALSE, results = "asis"}
answerlist(c(correct, incorrect), markup = "markdown")
```

bookdown figure number formattiing: both sequential numbering and section numbering

When using bookdown (single document), if I set both section_numbering = 'yes' and fig_caption = 'yes', the figures are numbered X.2 (where X is the section number). If section_number = 'no', the figures are numbered sequentially (Fig 1, 2 ...), but sections numbers are lost.
Is there a way to get figures numbered sequentially without losing the section numbers? In the example below, I would like to have both the sections figures numbered as 1 and 2.
Thank you.
---
output:
bookdown::html_document2:
fig_caption: yes
number_sections: yes
---
# header 1
Reference example: \#ref(fig:plotcars):
```{r plotcars, fig.cap = "A car plot"}
plot(cars)
```
# header 2
Reference example: \#ref(fig:plotcars2):
```{r plotcars2, fig.cap = "A car plot"}
plot(cars)
```
I just added a new argument global_numbering to the dev version of bookdown. You can test the dev version via
remotes::install_github('rstudio/bookdown')
Example:
---
output:
bookdown::html_document2:
fig_caption: true
number_sections: true
global_numbering: true
---
# header 1
Reference example: \#ref(fig:plotcars):
```{r plotcars, fig.cap = "A car plot"}
plot(cars)
```
# header 2
Reference example: \#ref(fig:plotcars2):
```{r plotcars2, fig.cap = "A car plot"}
plot(cars)
```

RMarkdown: How to use hooks on individual chunks?

I want to use knitr hooks on individual chunks using the datacamp/tutorial package. As per the following document, I get to set two options of height and greedy by using tutorial::go_interactive(greedy=FALSE, height=500)
How can I set different variables for individual chunks using knitr_hooks?
For eg., For the first chunk I want to set it up as greedy=TRUE, and for the second one, I want greedy=FALSE.
---
title: "Example Document"
author: "Your name here"
output:
html_document:
self_contained: false
---
```{r, include=FALSE}
tutorial::go_interactive()
```
Here's an example of a Python fiddle/
```{python}
a = 2
b = 3
print(a + b)
```
```{python}
x = 2
y = 3
print(x + y)
```
Never mind. Found the answer here
You have to set tut = FALSE on the chunk to knit it as a normal chunk.
```{r, include=FALSE}
tutorial::go_interactive()
```
Here's an example of a Python fiddle/
```{python}
a = 2
b = 3
print(a + b)
```
```{python, tut=FALSE}
x = 2
y = 3
print(x + y)
```

How to get a newline in a figure caption in Rmarkdown bookdown pdf:document2

I'm using knitr in RStudio to write an rmarkdown bookdown:pdf:document2 document.
I have two plots, plotted side-by-side with gridExtra, and labelled A and B. I want to put a newline in the output of the figure caption, as defined with fig.cap, between the caption for A and that for B, but I am stumped. I have tried:
\n - ignored as if it was not there
\\n - undefined control sequence
\\\n - Argument of #tempf has an extra }.
\\\\n - prints "\n" (getting a bit silly here)
double space - does nothing
I even tried, out of desperation, HTML style newlines, which I can't figure out how to display here, but I didn't expect them to work and they didn't.
It's possible in LaTeX so surely there is a way...
NOTE: this is not a duplicate of Split r chunk header across lines in knitr as that is asking how to split a long caption in a chunk header across lines in the code, and I am asking how to do so in the output.
Susannah
---
title: "MRR captions"
author: "Susannah Cowtan"
date: "14 December 2018"
output:
bookdown::pdf_document2:
citation_package: natbib
number_sections: no
toc: no
keep_tex: true
bookdown::html_document2: null
header-includes:
- \usepackage{float}
- \usepackage{booktabs}
fontsize: 11pt
papersize: A4
---
```{r knitr_setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
```
```{r plot-mtcars, fig.height = 3, fig.width = 4, fig.cap = "A: foo bar baz \nB: foobar"}
plot(mpg ~ wt, data = mtcars)
```
Instead of a newline, you may consider using sub-figures, e.g.
---
title: "MRR captions"
author: "Susannah Cowtan"
date: "14 December 2018"
output:
bookdown::pdf_document2:
keep_tex: true
header-includes:
- \usepackage{subfig}
---
See Figure \#ref(fig:plot-cars), which contains Figure \#ref(fig:plot-cars1) and Figure \#ref(fig:plot-cars2).
```{r plot-cars, fig.height = 3, fig.width = 4,, out.width='49%', fig.cap='Two plots', fig.subcap = c('foo bar baz', 'foobar')}
plot(mpg ~ wt, data = mtcars)
plot(cars)
```
You can do this by inserting the appropriate LaTeX commands, but the output is, in my humble opinion, not very pleasant to look at.
Option 1: caption package
Include the caption package by adding - \usepackage{caption} to the header-includes, then use the \newline command in your caption.
```{r plot-mtcars, fig.height = 3, fig.width = 4, fig.cap = "A: foo bar baz \\newline{}B: foobar"}
plot(mpg ~ wt, data = mtcars)
```
Option 2: force a linebreak via a long line
Adding enough horizontal white-space will also cause a linebreak. However, the caption will no longer appear to be centered.
```{r plot-mtcars, fig.height = 3, fig.width = 4, fig.cap = "A: foo bar baz \\hspace{\\textwidth}B: foobar"}
plot(mpg ~ wt, data = mtcars)
```
See TeX stackexchange for details.

Resources