Generate Moodle exercises with images using the exams package - r

I am using the exams package, I want to generate some Moodle exercises with it which incorporate some images. Although using this code in a *rmd file:
```{r, echo = FALSE, results = "hide"}
exams::include_supplement("ae1_2_1e2.png")
```
Question
========
Question text:
\centering
$\includegraphics[width=0.55 \textwidth] {ae1_2_1e2.png}$
Answerlist
----------
* answer a
* answer b
* answer c
* answer d
Solution
========
Answerlist
----------
* True
* False
* False
* False
Meta-information
================
exname: ae1_2_1
extype: schoice
exsolution: 1000
exshuffle: 4
Which produces this results in Moodle:
Another question is, does the package allows to use images as options in the Moddle exercises (i.e. schoice)? Example:
```{r, echo = FALSE, results = "hide", out.width = "20%"}
exams::include_supplement(c("ae4_3_2_1e2.png","ae4_3_2_3e4.png"))
```
Question
========
For a right-tailed test (using the Neyman-Pearson criteria), which would be the rejection region for a t-test (independent samples)?
Answerlist
----------
* \ ![](ae4_3_2_1e2.png) $\bigg]-\infty;-t_{1-\frac{\alpha}{2};(n_1+n_2-2)}\bigg] \cup \bigg[t_{1-\frac{\alpha}{2};(n_1+n_2-2)};+\infty\bigg[$.
* \ ![](ae4_3_2_1e2.png) $\bigg]-\infty;-t_{1-\frac{\alpha}{2};(n_1-n_2)}\bigg] \cup \bigg[t_{1-\frac{\alpha}{2};(n_1-n_2)};+\infty\bigg[$.
* \ ![](ae4_3_2_3e4.png) $\bigg[t_{1-\alpha;(n_1-n_2)};+\infty\bigg[$.
* \ ![](ae4_3_2_3e4.png) $\bigg[t_{1-\alpha;(n_1+n_2-2)};+\infty\bigg[$.
SOLVED
You cannot have the same image file in different options. If you want to use the same image, you have to produce a copy of it and use a different name.
So the new code:
```{r, echo = FALSE, results = "hide", out.width = "20%"}
exams::include_supplement(c("ae4_3_2_1.png","ae4_3_2_3.png","ae4_3_2_2.png","ae4_3_2_4.png"))
```
Question
========
For a right-tailed test (using the Neyman-Pearson criteria), which would be the rejection region for a t-test (independent samples)?
Answerlist
----------
* \ ![](ae4_3_2_1.png){width=20%} $\bigg]-\infty;-t_{1-\frac{\alpha}{2};(n_1+n_2-2)}\bigg] \cup \bigg[t_{1-\frac{\alpha}{2};(n_1+n_2-2)};+\infty\bigg[$.
* \ ![](ae4_3_2_2.png){width=20%} $\bigg]-\infty;-t_{1-\frac{\alpha}{2};(n_1-n_2)}\bigg] \cup \bigg[t_{1-\frac{\alpha}{2};(n_1-n_2)};+\infty\bigg[$.
* \ ![](ae4_3_2_3.png){width=20%} $\bigg[t_{1-\alpha;(n_1-n_2)};+\infty\bigg[$.
* \ ![](ae4_3_2_4.png){width=20%} $\bigg[t_{1-\alpha;(n_1+n_2-2)};+\infty\bigg[$.
Meta-information
================
exname: RTT
extype: schoice
exsolution: 0001
exshuffle: TRUE
And the result (thanks to #Achim):

When you are using R/Markdown (.Rmd) exercises, then Markdown should be used for including static graphic files:
Question text:
\
![](ae1_2_1e2.png)
Inclusion of LaTeX is possible but only for mathematical equations - putting the \includegraphics{} into math mode is not appropriate here.
An example template that includes a static PNG file is available at: http://www.R-exams.org/templates/Rlogo/. Note that the backslash embeds the image in such a way that no caption is added here. See the pandoc documentation for more details: https://pandoc.org/MANUAL.html#images
Below is also a worked example (mice.Rmd) for images as answers in Moodle, restricting the width to the same value for all images:
```{r, include=FALSE}
download.file("https://i.pinimg.com/originals/f7/7b/17/f77b173fb104d07130697c9d3a024e75.png", "a.png")
download.file("https://upload.wikimedia.org/wikipedia/en/thumb/f/fe/Speedy_Gonzales.svg/1200px-Speedy_Gonzales.svg.png", "b.png")
download.file("https://www.disneyclips.com/images3/images/basil-great-mouse-detective.png", "c.png")
```
Question
========
Which of these cartoon mice belongs to the Disney franchise?
Answerlist
----------
* ![](a.png){width=20%}
* ![](b.png){width=20%}
* ![](c.png){width=20%}
Meta-information
================
exname: Mice
extype: schoice
exsolution: 001
exshuffle: TRUE
In Moodle this is rendered in the following way:

Related

How to avoid "! LaTeX Error: Environment axis undefined" when using include_tikz with pgfplots?

I have successfully included in an R/exams .Rmd file several graphics made in TikZ. The same does not happen when I try to include a plot under pgfplots using include_tikz(). Whenever \begin {axis} and \end {axis} are included, beware of the error "! LaTeX Error: Environment axis undefined".
In the RStudio console the legend appears: "This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) (preloaded format = pdflatex) restricted \ write18 enabled.entering extended mode", even having enabled in TexStudio write-18. None of these messages appear when I include other TikZ graphs other than pgfplots.
Any TikZ graph works when run in TexMaker or TexStudio, which indicates that it is not a problem of the absence of LaTeX libraries or packages.
I include a part of my code, adapted from https://www.latex4technics.com/?note=1HCT:
```{r datos1, echo = FALSE, results = "hide"}
library(exams)
typ <- match_exams_device()
image01<-'
\\begin{tikzpicture}
\\begin{axis}[legend pos=south east]
\\addlegendimage{empty legend}
\\addplot {sqrt(x)};
\\addplot {ln(x)};
\\addlegendentry{\\hspace{-.6cm}\\textbf{A title}}
\\addlegendentry{$\\sqrt{x}$}
\\addlegendentry{$\\ln{x}$}
\\end{axis}
\\end{tikzpicture}
'
```
```{r grafica01, echo = FALSE, results = "asis"}
include_tikz(image01, name = "grafiko1", markup =
"markdown",format = typ,library = c("arrows"),packages =
"booktabs",width = "7cm",header = "\\usepackage{/home/r-
exams/Documentos/NuevoRStudio/Rmarkdowns/
Esqueleto/exercises/schoice/
LaboratorioTikZ/3dplot}")
```
The answer is right there in your question title. You need to include the pgfplots package:
include_tikz(image01, packages = "pgfplots", ...)
The other packages, library, and header arguments from the call in your question are not needed.
The reason is that for include_tikz() you just use the {tikzpicture} code while in the full .tex file that you linked you additionally have:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
...
\end{tikzpicture}
\end{document}
Note the \usepackge{pgfplots} in the second line!

R: Oxforddown numbers all my lines in pdf... What is the issue?

I am preparing my master dissertation and took the challenge of doing it all in R together with 2 students.
I used the template from Ulrik Lyngs. Modified the index.Rmd. But now all my lines are numbered...
See infra for index.Rmd code.
What I had to do to make it work (build the thesis), is download MacTex and uninstall tinyTex. But I really don't know what went wrong.
---
#####################
## thesis metadata ##
#####################
title: |
Thesis title
author: Faes, E.
college: Master in Finance
university: Antwerp Management School
university-logo: templates/beltcrest.pdf
submitted-text: A thesis submitted for the degree of
degree: Master in Finance
degreedate: June 2021
abstract: |
`r paste(readLines("front-and-back-matter/_abstract.Rmd"), collapse = '\n ')`
acknowledgements: |
`r paste(readLines("front-and-back-matter/_acknowledgements.Rmd"), collapse = '\n ')`
dedication: For Yihui Xie
abbreviations: "front-and-back-matter/abbreviations" # path to .tex file with abbreviations
#######################
## bibliography path ##
#######################
bibliography: references.bib
########################
## PDF layout options ###
#########################
masters-submission: false
corrections: false # correction highlighting
## binding / margins ##
page-layout: twoside #'nobind' for equal margins (PDF output), 'twoside' for two-sided binding (mirror margins and blank pages), leave blank for one-sided binding (left margin > right margin)
## position of page numbers ##
ordinary-page-number-foot-or-head: foot #'foot' puts page number in footer, 'head' in header
ordinary-page-number-position: C #C = center, R = right, L = left. If page layout is 'twoside', O = odd pages and E = even pages. E.g. RO,LE puts the page number to the right on odd pages and left on even pages
chapter-page-number-foot-or-head: foot #you may want it to be different on the chapter pages
chapter-page-number-position: C
## position of running header ##
running-header: true #indicate current chapter/section in header?
running-header-foot-or-head: head
running-header-position-leftmark: LO #marks the chapter. If layout is 'nobind', only this is used.
running-header-position-rightmark: RE #marks the section.
draft-mark: false # add a DRAFT mark?
draft-mark-foot-or-head: foot ##'foot' = in footer, 'head' = in header
draft-mark-position: C
## section numbering ##
section-numbering-depth: 2 # to which depth should headings be numbered?
## tables of content ##
toc-depth: 2 # to which depth should headings be included in table of contents?
lof: true # include list of figures in front matter?
lot: true # include list of tables in front matter?
mini-toc: false # include mini-table of contents at start of each chapter? (this just prepares it; you must also add \minitoc after the chapter titles)
mini-lot: false # include mini-list of tables by start of each chapter?
mini-lof: false # include mini-list of figures by start of each chapter?
## code block spacing ##
space-before-code-block: 10pt
space-after-code-block: 8pt
## linespacing ##
linespacing: 22pt plus2pt # 22pt is official for submission & library copies
frontmatter-linespacing: 17pt plus1pt minus1pt #spacing in roman-numbered pages (acknowledgments, table of contents, etc.)
### other stuff ###
abstractseparate: false # include front page w/ abstract for examination schools?
hidelinks: true # false to highlight clickable links with a colored border
includeline-num: true
### citation and bibliography style ###
bibliography-heading-in-pdf: Works Cited
# biblatex options #
# unless you run into 'biber' error messages, use natbib as it lets you customise your bibliography directly
use-biblatex: true
bib-latex-options: "style=authoryear, sorting=nyt, backend=biber, maxcitenames=2, useprefix, doi=true, isbn=false, uniquename=false" #for science, you might want style=numeric-comp, sorting=none for numerical in-text citation with references in order of appearance
# natbib options #
# natbib runs into fewer errors than biblatex, but to customise your bibliography you need to fiddle with .bst files
use-natbib: false # to use natbib, set this to true, and change "output:bookdown::pdf_book:citation_package:" to "natbib"
natbib-citation-style: authoryear #for science, you might want numbers,square
natbib-bibliography-style: ACM-Reference-Format #or plainnat or some .bst file you download
#####################
## output options ##
#####################
output:
bookdown::pdf_book:
citation_package: biblatex
template: templates/template.tex
keep_tex: true
#pandoc_args: "--lua-filter=scripts_and_filters/colour_and_highlight.lua"
bookdown::bs4_book:
css:
- templates/bs4_style.css
- templates/corrections.css # remove to stop highlighting corrections
theme:
primary: "#6D1919"
repo: https://github.com/ulyngs/oxforddown
#pandoc_args: "--lua-filter=scripts_and_filters/colour_and_highlight.lua"
bookdown::gitbook:
css: templates/style.css
config:
sharing:
facebook: false
twitter: yes
all: false
bookdown::word_document2:
toc: true
link-citations: true
documentclass: book
always_allow_html: true #this allows html stuff in word (.docx) output
# The lines below make the 'knit' button render the whole thesis to PDF, HTML, or Word
# When outputting to PDF, you can clean up the files LaTeX generates by running
# 'file.remove(list.files(pattern = "*.(log|mtc|maf|aux|bbl|blg|xml)"))' in the R console
knit: (function(input, ...) {bookdown::render_book(input, output_format = "bookdown::pdf_book")})
#knit: (function(input, ...) {bookdown::render_book(input, output_format = "bookdown::bs4_book")})
#knit: (function(input, ...) {bookdown::render_book(input, output_format = "bookdown::gitbook")})
#knit: (function(input, ...) {bookdown::render_book(input, output_format = "bookdown::word_document2")})
---
```{r install_packages, include=FALSE}
source('scripts_and_filters/install_packages_if_missing.R')
```
```{r create_chunk_options, include=FALSE, eval=knitr::is_latex_output()}
source('scripts_and_filters/create_chunk_options.R')
source('scripts_and_filters/wrap_lines.R')
```
<!--
Include the create_chunk_options chunk above at the top of your index.Rmd file
This will include code to create additional chunk options (e.g. for adding author references to savequotes)
and to make sure lines in code soft wrap
If you need to create your own additional chunk options, edit the file scripts/create_chunk_options.R
-->
<!-- This chunk includes the front page content in HTML output -->
```{r ebook-welcome, child = 'front-and-back-matter/_welcome-ebook.Rmd', eval=knitr::is_html_output()}
```
Numbered lines are very nice for reviewers. You don't want them in the final submitted version of the thesis, but it's nice for a reviewer to be able to say "You repeated the word Thanks on line 13", instead of making them count lines themselves.
To turn them on, keep
includeline-num: true
in your YAML. To turn them off, set this to false.

Figures showing at the end of the document in R markdown

I have been working on this issue since yesterday and have checked almost all the solutions but I'm still not able to solve this issue. All the figures and tables I put in the document shows at the end of the document instead of where I place them.
fig_cap : yes
keep_tex : yes
floatsintext : no
figurelist : no
tablelist : no
footnotelist : no
linenumbers : no
mask : no
draft : no
documentclass : "apa6"
classoption : "man"
output : papaja::apa6_pdf
header-includes:
\usepackage{float}
\floatplacement{figure}{H}
I have added float package as well as fig_cap in yaml above as recommended in some other solutions. Also I have globally defined fig.pos = H
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.pos = 'H')
```
This is the histogram I'm trying to showin between my paragraphs (it moves down to the end of document as soon as I use fig.cap)
```{r Histogram, out.width = "90%", out.height = "100%", fig.align = "center", fig.pos='H', out.extra = '',fig.cap= "eee", echo=FALSE}
histogram_plot <- ggplot(dataset1, aes(x=SocialNetworkUse))+
geom_histogram(bins = 30) +
labs(x="Social Network Use (Hours)", y = "Respondents")
histogram_plot
```
Now this is the what I'm getting in my tex file
\begin{figure}[H]
{\centering \includegraphics[width=0.9\linewidth,height=1\textheight,]{ANLY-699_files/figure-latex/Histogram-1}
}
\caption{eee}\label{fig:Histogram}
\end{figure}
However the fff files shows this output
\begin{figure*}[hbt]
\ifnextchar[{\eatarg}{}
[H]
{\centering \includegraphics[width=0.9\linewidth,]{ANLY-699_files/figure-latex/Histogram-1}
}
\caption{foff}\label{fig:Histogram}
\end{figure*}
Fairly new to Rmarkdown and not sure what's causing the figures to not stay in place. Any help would be appreciated.
I just had to add figsintext : yes in my Yaml file to solve the issue.

Text (not syntax) highlighting in Rmarkdown/Papaja

I'm compiling a report using Papaja and Rmarkdown, and I want to highlight various text throughout. Doing so with latex or pure Rmarkdown is easy, but I'm receiving an "undefined control sequence" error when I compile the report to PDF using Papaja's application of Knitr.
A similar question about text highlighting within a single Rmarkdown file was answered here: RMarkdown / pandoc fails to knit Pdf with latex color commands. I'd like to know if an answer exists for multiple Rmarkdown files using Papaja.
I'll include a minimal example below.
1) File called papaja_file.Rmd
---
# https://crsh.github.io/papaja_man/index.html
title : "Some Title"
shorttitle : "HEADER"
author:
- name : "Name R Here"
affiliation : "1"
corresponding : yes # Define only one corresponding author
address : "Include addresss"
email : "randomemail#usa.edu"
affiliation:
- id : "1"
institution : "Any University"
author_note: |
....
abstract: |
Text here for abstract.
keywords : "Keyword1, keyword2, keyword3"
bibliography : ["references.bib"]
figsintext : no
figurelist : no
tablelist : no
footnotelist : no
lineno : yes
lang : "english"
class : "man"
output : papaja::apa6_pdf
---
```{r load_packages, include = FALSE}
library("papaja")
```
```{r analysis_preferences}
# Seed for random number generation
set.seed(42)
```
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.path = 'figures/', echo = TRUE, warning = FALSE, message = FALSE)
```
```{r child = 'child_document.Rmd'}
```
\newpage
# References
```{r create_references, echo = F}
r_refs(file = "references.bib")
```
\setlength{\parindent}{-0.5in}
\setlength{\leftskip}{0.5in}
Notice that it references a single child Rmarkdown document.
2) The child document with text, called child_document.Rmd
---
output:
pdf_document:
includes:
in_header: preamble.tex
---
One sentence without highlighting. \hl{Another with highlighting.}
3) The preamble, called preamble.tex
\usepackage{color}
\usepackage{soul}
\definecolor{lightblue}{rgb}{0.90, 0.95, 1}
\sethlcolor{lightblue}
Knitting the main papaja file produces the error. Removing the \hl command within the child document allows the pdf to compile without issue.
Result after putting YAML header within the main papaja document rather than the child:
The YAML header in your child document is not evaluated, c.f.
The master document, for example, consists of the YAML front matter and includes the children, which are themselves R Markdown documents without a YAML front matter.
https://crsh.github.io/papaja_man/tips-and-tricks.html#splitting-an-r-markdown-document
But you can include your preamble.tex in you master file using:
output:
papaja::apa6_pdf:
includes:
in_header: preamble.tex
c.f. https://github.com/rstub/stackoverflow/commit/a92a67d4721ee9c06e995b08adbf8cb89daebcb4
Result:

How to justify (to both sides) text in R Markdown when knitting in pdf output

I have looked for ways to control the alignment of the text, however I could not find anything for PDF outputs.
There is an existing answer, but related to HTML output only: How to justify the text to both sides when knitting html in rmarkdown.
R Markdown should default to using justified text. However, if you only want to export to PDF, we can directly use LaTeX commands within the document.using the standard arguments \centering \raggedright and \raggedleft, as explained here.
Here is a minimal example:
---
output: pdf_document
---
```{r, include = FALSE}
devtools::install_github("coolbutuseless/lipsum")
library(lipsum)
```
**Default**
`r lipsum[1]`
\centering
**Centered Text**
`r lipsum[1]`
\raggedright
**Ragged Right**
`r lipsum[1]`
\raggedleft
**Ragged Left**
`r lipsum[1]`
If you want to revert to justified text, you can use the ragged2e LaTeX package. You will need to load this within the YAML by adding:
---
output: pdf_document
header-includes:
- \usepackage[document]{ragged2e}
---
\raggedleft
**Ragged Left**
`r lipsum[1]`
\justifying
**Revert to Justified**
`r lipsum[1]`
Edit
If you are using the papaja template you need to include all the YAML. Not providing an author, shorttitle or another other field will cause it to crash.
---
title : "The title"
shorttitle : "Title"
author:
- name : "First Author"
affiliation : "1"
corresponding : yes # Define only one corresponding author
address : "Postal address"
email : "my#email.com"
- name : "Ernst-August Doelle"
affiliation : "1,2"
affiliation:
- id : "1"
institution : "Wilhelm-Wundt-University"
- id : "2"
institution : "Konstanz Business School"
author_note: |
Add complete departmental affiliations for each author here. Each new line herein must be indented, like this line.
Enter author note here.
abstract: |
Enter abstract here. Each new line herein must be indented, like this line.
keywords : "keywords"
wordcount : "X"
bibliography : ["r-references.bib"]
figsintext : no
figurelist : no
tablelist : no
footnotelist : no
lineno : yes
mask : no
class : "man"
output : papaja::apa6_pdf
header-includes:
- \usepackage[document]{ragged2e}
---
```{r load_packages, include = FALSE}
library(lipsum)
```
\justifying
**Default**
`r lipsum[1]`

Resources