-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRmd_with_LaTeX.Rmd
486 lines (340 loc) · 13.4 KB
/
Rmd_with_LaTeX.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
---
title: "R Markdown with LaTeX"
author: "Rob Donald"
date: "`r format(Sys.time(), '%A %d %B %Y')`"
output:
pdf_document:
fig_caption: true
toc: true
toc_depth: 2
urlcolor: blue
---
```{r setup, include=FALSE}
# The fig.pos = 'h' tells LaTeX to put the figure where you ask for it
knitr::opts_chunk$set(echo = TRUE,fig.height=8,fig.width=12,fig.pos = 'h')
options(width=1500)
```
```{r library_setup, include=FALSE}
suppressMessages({suppressWarnings({
library(dplyr)
library(readr)
library(lubridate)
library(here)
library(ggplot2)
library(RobsRUtils)
library(pander)
})})
```
```{r echo=FALSE}
theme.report <- theme_bw() + theme(plot.title = element_text(colour="black"
,size=24
,angle=0
,hjust=0.5,vjust=1.0
,face="plain")
,axis.text.x = element_text(colour="black"
,size=18
,angle=0
,hjust=0.5,vjust=0.6
,face="plain")
,axis.text.y = element_text(colour="black"
,size=12
,angle=0
,hjust=0.0,vjust=0.6
,face="plain")
,axis.title = element_text(colour="black"
,size=18
,angle=0
,hjust=0.5,vjust=0.6
,face="plain")
)
```
# Introduction
This set of notes shows some examples of using \LaTeX\ with R markdown.
The idea is to give examples which help if you are reasonably comfortable
with R markdown but want *some* of the customisation of using LaTeX without
having to become a LaTeX guru \footnote{Although if you do get proficient
in this stuff you may well get the guru title}. The code that generates the
.pdf output is in the .Rmd file in this repo.
# What is \LaTeX? {#Sec_WhatIsLaTex}
Well if you have been 'Knit'ing to PDF inside RStudio you have been using
LaTeX all the time. You may have already used things like \\newpage to
tidy up a document. The \\newpage is actually a LaTeX command which is being
detected by Knitr as it processes the document.
LaTeX is used extensively in academia particularly in any subject that requires
a lot of maths notation. It is a different way of thinking about documents. You
write your document in plain text and add in the various commands that format the
document into something that looks nice. It means you can produce a PDF document
with formulas and figures and tables without ever going near Word. But it is
not for everyone. If you need a WYSIWYG editor then this is not for you.
In the past you would need to use a LaTeX editor of some kind (e.g. the cross platform open source program [TeXMaker](http://www.xm1math.net/texmaker/)). With the advent of RStudio and
R Markdown (*which I assume you are at least partly familiar with*) you can now
write well formatted PDF documents with very little knowledge of LaTeX.
This set of notes will show you how you can extend your documents by using
a small amount of LaTeX code in the text portion of your .Rmd R markdown
document.
NOTE: if you go down this route you can't flip back to HTML output. The Knitr
package will get a bit upset and probably miss out some of the LaTeX commands. It will look like it has worked, there will just be missing bits (give it a try ...)
## Some History {#SubSec_LatexHistory}
LaTeX is actually a typesetting programming language and was developed
by Leslie Lamport in 1983. See this link for a more detailed
description [LaTeX History](https://en.wikipedia.org/wiki/LaTeX#History).
It is a layer of code over the top of the typesetting language \TeX which
was developed by the famous computer scientist Donald Knuth in 1978. See
this link for more details [Tex History](https://en.wikipedia.org/wiki/TeX)
# Useful YouTube links
+ [LaTeX Tutorial 1 - Creating a LaTeX Document](https://www.youtube.com/watch?v=SoDv0qhyysQ)
The above link is the start of a very useful series of videos
by Michelle Krummel.
# Font Sizes
\begin{Large}
Some Large (with a capital 'L') text
\end{Large}
\begin{large}
Some large text
\end{large}
\begin{normalsize}
Some normalsize text
\end{normalsize}
Compare this default R markdown line to the above 'normalsize' text.
\begin{small}
Some small text which runs over several
lines of text and allows us to put in more information
in a smaller space. Which can be useful if the information
is very dense.
\end{small}
\begin{footnotesize}
This is footnotesize. Useful size for tables and other hard to fit in things.
\end{footnotesize}
# Size and Position of Figures
This can be really awkward as \LaTeX\ often thinks *it* knows best.
The web is full of stuff that doesn't work for output to .pdf documents.
Here are some commands to try for controlling the position and size of figures.
## Size Using out.width and out.height
The technique I use all the time is to import the picture into the document
with an R chunk. Inside the R chunk you use:
+ knitr::include_graphics()
You add options to the chunk header.
```{}
{r, out.width='18cm',out.height='12cm'}
```
This gives:
```{r, out.width='18cm',out.height='12cm'}
image.path <- here('images','GitWorkflow.png')
knitr::include_graphics(path = image.path)
```
The 18 cm seems to work for an A4 page which is 21 cm wide. You can adjust
the height to suit your image.
Let's half the size.
```{}
{r, out.width='9cm',out.height='6cm'}
```
This gives:
```{r, out.width='9cm',out.height='6cm'}
image.path <- here('images','GitWorkflow.png')
knitr::include_graphics(path = image.path)
```
### Sometimes even this doesn't work
The problem with the above is that sometimes even this doesn't work and it
can be *very* frustrating. The out.width and out.height options are just ignored. My best guess
at this is that the original image size is to big *or* too small for the resizing
to work. This is hinted at in this web post https://github.com/yihui/knitr/issues/1477.
The way I fix this is usually to resize the image to something that looks about right on an
A4 page on my Macbook screen and then screen grab it using the Mac's Cmd-Shift-4 sequence. I have
this set to capture as .pdf but the default is .png. This seems to give me something that will
resize most of the time. Tedious eh (best Canadian accent).
\newpage
## Centre the Image
Now we can try to centre the image. The next two attempts *__don't__* work
for me despite lots of the internet telling you they will.
<!-- MAJOR MAJOR PAIN -->
<!-- \begin{center} -->
```{r, out.width='9cm',out.height='6cm'}
image.path <- here('images','GitWorkflow.png')
knitr::include_graphics(path = image.path)
```
<!-- \end{center} -->
<!-- NOTE the four backticks to get this to render correctly -->
I had to update my TexLive installation on 2024-11-11
This seems to have caused a major screw up using the following code, i.e.
knitr::include_graphics(path = image.path) within "\\begin{center}\\end{center}"
causing 'Knit' to fail completely.
Directly in the text part of the R markdown.
```{}
\begin{center}
\include_graphics('images/GitWorkflow.png')
\end{center}
```
This doesn't even produce the plot!
## Using fig.align="center"
This technique *does* work. Add this into the chunk header.
```{}
{r, out.width='9cm',out.height='6cm',fig.align="center"}
```
This gives:
```{r, out.width='9cm',out.height='6cm',fig.align="center"}
image.path <- here('images','GitWorkflow.png')
knitr::include_graphics(path = image.path)
```
\newpage
---
*Here is a link to a constantly referenced article on the web about this stuff.
Note that it is biased towards HTML output*
[ZevRoss Article](https://www.zevross.com/blog/2017/06/19/tips-and-tricks-for-working-with-images-and-figures-in-r-markdown-documents/#use-dpi-to-change-the-resolution-of-images-and-figures)
---
So let's add a 'Large' title and caption
\begin{Large}
\begin{center}
Git Workflow
\end{center}
\end{Large}
```{r echo=FALSE, fig.align="center", out.height='8cm', out.width='12cm'}
image.path <- here('images','GitWorkflow.png')
knitr::include_graphics(path = image.path)
```
Figure1: The above diagram shows a typical Git workflow using
a cloud based Git provider (e.g. Bitbucket or Github) as the central
repository for the team's work.
\newpage
## Multiple figures
I came across this link https://bookdown.org/yihui/rmarkdown-cookbook/figures-side.html
which shows a technique for putting figures side by side. It works!
```{}
{r, figures-side, fig.show="hold", out.width="50%"}
par(mar = c(4, 4, .1, .1))
plot(cars)
plot(mpg ~ hp, data = mtcars, pch = 19)
```
Using our .png images like this:
```{r, figures-side,fig.show="hold", out.width="50%"}
par(mar = c(4, 4, .1, .1))
image.path <- here('images','GitWorkflow.png')
knitr::include_graphics(path = image.path)
image.path <- here('images','GitWorkflow_2.png')
knitr::include_graphics(path = image.path)
```
Be warned that this seems quite fragile and I was able to easily break it by using dissimilar
image sizes or trying to add a caption with fig.cap="abc".
# Centred Text
```{}
\begin{center}
Some centred text on a line
\end{center}
```
Gives this:
\begin{center}
Some centred text on a line
\end{center}
\newpage
# Maths and Greek Symbols
This link, https://rpruim.github.io/s341/S19/from-class/MathinRmd.html, gives a
good overview of getting standard maths notation into your R markdown document.
Here is an example:
```{}
\begin{align*}
a & = b \\
X &\sim {\sf Norm}(10, 3) \\
5 & \le 10
\end{align*}
```
which will produce this text:
\begin{align*}
a & = b \\
X &\sim {\sf Norm}(10, 3) \\
5 & \le 10
\end{align*}
# Quarto Equation Numbering
This is really quite unpleasant.
* \url{https://github.com/quarto-dev/quarto-cli/issues/2275}
```{}
<!-- even though we are using {flalign} we still need to use a & single line or &\\ multiple line to force -->
<!-- the left justification -->
<!-- See these links -->
<!-- https://github.com/quarto-dev/quarto-cli/issues/2275 -->
<!-- https://quarto.org/docs/authoring/cross-references.html#equations -->
<!-- Equation numbering: -->
<!-- The key is this line \numberwithin{equation}{subsection} in the -->
<!-- include-in-header: top yaml bit -->
```
```{}
include-in-header:
text: \addtokomafont{disposition}{\rmfamily}
\usepackage{amsmath}
\numberwithin{equation}{section} #{section|subsection}
\usepackage{xurl}
\usepackage{typearea}
```
# Internal Section Links
This is how to reference an internal section
From this link (answered May 19 '14 at 9:11 by hoijui:)
https://stackoverflow.com/questions/2822089/how-to-link-to-part-of-the-same-document-in-markdown
1. Create the anchor
2. Reference the anchor
* Create the anchor
You do this by adding a link name in curly brackets to the header you will be referencing.
```{r}
# My Useful Section {#Sec_MyUsefulBit}
```
* Reference the anchor
Somewhere in your *body text* use the normal syntax for a link
```{}
[link name](link)
```
so for example
```{}
See the section on [What is LaTex](#Sec_WhatIsLaTex)
```
See the section on [What is LaTex](#Sec_WhatIsLaTex)
This also works for sub sections, i.e. H2 headers
Here is the markdown:
```{}
See this paragraph [History of LaTex](#SubSec_LatexHistory) for more details.
```
which will give this output in your document.
See this paragraph [History of LaTex](#SubSec_LatexHistory) for more details.
# Rotating Pages
Make sure the .Rmd YAML header has this in it:
```{}
header-includes:
- \usepackage{pdflscape}
```
Then before a chunk something like this:
```{}
\newpage
\begin{landscape}
```
With a chunk specification like:
```{}
{r echo=FALSE, fig.align='center'}
titleStr <- 'Percent Marked Monitoring Time (Filtered Data)'
subtitleStr <- 'Kids BIT'
p <- Generate_Marking_PC_MonTime(plot_mpcmt_filtered
,titleStr = titleStr
,subtitleStr = subtitleStr)
print(p)
```
Followed by a closing section after the chunk:
```{}
\end{landscape}
```
NOTE: the ```fig.align='center'``` is critical and some web references say that
this does not work with ```knitr::include_graphics()```, although I have not confirmed that.
# Slide Presentations
## Beamer
https://rmarkdown.rstudio.com/articles_beamer.html
Also see my R project ```KidsBIT_DataPrep```, file ```KidsBIT_ProgressOverview_April_2021.Rmd```
## xaringan
https://emitanaka.org/slides/rladiesSSA2020
\newpage
# References
This is an example of creating a references page.
\begin{footnotesize}
\begin{center}Footnote Size Links\end{center}
\begin{itemize}
\item{[1] \url{https://www.stata.com/manuals13/pss.pdf} \tiny{(Accessed 2019-05-02)}}
\item{[2] \url{https://en.wikipedia.org/wiki/Sample_size_determination} \tiny{(Accessed 2019-05-03)}}
\item{[3] \url{https://en.wikipedia.org/wiki/Power_(statistics)} \tiny{(Accessed 2019-05-03)}}
\item{[4] \url{https://en.wikipedia.org/wiki/Effect_size} \tiny{(Accessed 2019-05-03)}}
\item{[5] \url{https://en.wikipedia.org/wiki/Test_statistic} \tiny{(Accessed 2019-05-03)}}
\item{[6] \url{https://blog.minitab.com/blog/adventures-in-statistics-2/understanding-analysis-of-variance-anova-and-the-f-test} \tiny{(Accessed 2019-05-03)}}
\end{itemize}
\end{footnotesize}