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

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")
```

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 chunk inside LaTeX in an rmarkdown document

I am trying to get an R chunk run inside LaTeX code in the following rmarkdown document:
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\begin{enumerate}
\item
{
```{r}
x <- 2+3
x
```
}
\end{enumerate}
The output is:
But I want:
Could you please help me?
EDIT: I want the R chunk to be both evaluated (but result hidden) and its code shown. I have meanwhile found this solution, but maybe there is a simpler one: https://tex.stackexchange.com/questions/210003/how-can-i-nest-a-code-chunk-within-an-enumerate-environment-when-using-r-markdow
You need this? See here https://bookdown.org/yihui/rmarkdown-cookbook/raw-latex.html
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
```{=latex}
\begin{tabular}{ll}
x <- 2+3\\
x\\
\end{tabular}
```
In any of the following examples, you can substitute a double return instead of \\.
If you are wanting to just show those expressions then do not put it in a code chunk:
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\begin{enumerate}
\item
{
x <- 2 + 3\\x
}
\end{enumerate}
This will produce:
Otherwise, if you want to evaluate an inline expression use backticks and r:
---
title: "Untitled"
output: pdf_document
date: '2022-05-20'
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\begin{enumerate}
\item
{
`r x <- 2 + 3; x`
}
\end{enumerate}
Which produces:
Lastly, you can of course combine these two concepts to show the expression and evaluate the value by doing this:
x <- 2 + 3\\
`r x <- 2 + 3; x`
If your expression is more complex, I would recommend having the code chunk outside of your LaTeX for evaluation.
Update
For simpler expressions you could do something like:
```{r, include = F}
exprsn <- "x <- 2 + 3"
```
\begin{enumerate}
\item
{
`r exprsn`\\
`r eval(parse(text = exprsn)); x`
}
\end{enumerate}
Meanwhile, I found this: How can I nest a code chunk within an enumerate environment when using R Markdown?, which inspires the following solution:
---
title: "Untitled"
output:
pdf_document:
highlight: monochrome
date: '2022-05-20'
header-includes:
- \newcommand{\benum}{\begin{enumerate}}
- \newcommand{\eenum}{\end{enumerate}}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, results = "hide")
```
\benum
\item
```{r}
x <- 2+3
x
```
\eenum

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

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

Hide comments in R markdown

Is is possible to hide some comments in code when kniting using knitr / R markdown? Example:
---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document
---
```{r}
# Generate some data
rnorm(2)
## But keep this comment
```
When kniting I would like the first comment to disapear, but keep the second one somehow.
Here is a quick example of modifying the hook to change knitr behavior.
---
title: "SOSO"
author: "SO"
date: 2017-06-06
output: pdf_document
---
```{r setup-hook, echo=FALSE}
hook_in <- function(x, options) {
x <- x[!grepl("^#\\s+", x)]
paste0("```r\n",
paste0(x, collapse="\n"),
"\n```")
}
knitr::knit_hooks$set(source = hook_in)
```
```{r}
# Generate some data
# Lines that starts with `# ` will be removed from the rendered documents
rnorm(2)
## But keep this comment
## But lines that starts with `## ` will be kept
```
produces this
In fact, you can choose to show any lines of R code by passing numeric indices to the chunk option echo, e.g.
---
title: "SOSO"
author: "SO"
date: '2017-06-06'
output: pdf_document
---
```{r echo=4:7}
# Generate some data
rnorm(2)
## But keep this comment
```
See knitr documentation for more information.

Turning off title page in Rmd using knitr

Edit:
Desired result can almost be reached, when overriding pagestyle "plain" and using documentclass article.
\fancypagestyle{plain}{
\fancyhf{}
\fancyhead[RO,RE]{Header}
\fancyfoot[RO,RE]{\thepage}
}
The problem I am facing no is that the headsep (space between header and table) is greater on the first page. This seems to be because of \maketitle. When removing
$if(title)$
\maketitle
$endif$
from the (default) pandoc template everything works as expected.
Imho the same result should also be reachable (without editing the template) but using "title: false" in the yaml-header in my .rmd file. But the "\maketitle" command seems to be there anyways when looking at the generated .tex. Why is that?
Original Question:
I'm trying to turn off the titlepage when creating a pdf using knitr. The document contains a longtable with repeated headers.
I'm expecting a pdf, where all pages have header and footer Information (and headsep) as specified. In the running example below page 1 behaves differently. Attempt to disable titlepage was not successfull.
test.Rmd
---
author: "Fabian"
output: pdf_document
documentclass: report
classoption: notitlepage
params:
testParam: !r data.frame(a = 1:100, b = 2:101)
header-includes:
\usepackage{longtable}
\usepackage{xcolor}
\usepackage{hyperref}
\hypersetup{colorlinks = false}
\usepackage{geometry}
\geometry{a4paper, landscape, left = 13mm, right = 14mm, top = 5mm, bottom = 13mm, includeheadfoot}
\headsep = 5mm
\usepackage{graphicx}
\usepackage{lastpage}
\usepackage{fancyhdr}
\pagestyle{fancy}
\fancyhf{}
\fancyhead[RO,RE]{Header}
\fancyfoot[RO,RE]{\thepage}
---
```{r setup, include = F}
library(data.table)
```
\centering
\begin{longtable}{ll}
\hline
```{r createLatexheader, eval = T, echo = F, results = "asis"}
header <- names(data)
latexHaeder <- paste0(paste0(header, collapse = " & "), " \\\\ \n")
cat(latexHaeder)
```
\hline
\endhead
```{r createLatexdata, eval = T, echo = F, results = "asis"}
data <- params$testParam
setDT(data)
data[, ID := .I]
latexData <- data[, .(LATEX = paste0(.SD, collapse = " & ")), by = ID]$LATEX
latexData <- paste0(paste0(latexData, collapse = " \\\\ \n"), " \\\\ \n")
cat(latexData)
```
\end{longtable}
To turn \maketitle into a no-op, add the following to your header-includes:
\AtBeginDocument{\let\maketitle\relax}
Even if \maketitle is executed, this redefinition (delayed until \begin{document}) will do nothing.

Resources