prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R...

15
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . R programming prof. UAM dr hab. Tomasz Górecki [email protected] Department of Mathematical Statistics and Data Analysis Faculty of Mathematics and Computer Science Adam Mickiewicz University in Poznań Tomasz Górecki (UAM) R programming 1 / 13

Transcript of prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R...

Page 1: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R programming

prof. UAM dr hab. Tomasz Gó[email protected]

Department of Mathematical Statistics and Data AnalysisFaculty of Mathematics and Computer Science

Adam Mickiewicz University in Poznań

Tomasz Górecki (UAM) R programming 1 / 13

Page 2: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – idea

R Markdown provides an authoring framework for data science. You canuse a single R Markdown file to both save and execute code, and generatehigh quality reports that can be shared with an audience. R Markdownwas designed for easier reproducibility, since both the computing code andnarratives are in the same document, and results are automaticallygenerated from the source code. R Markdown supports dozens of staticand dynamic/interactive output formats.

Tomasz Górecki (UAM) R programming 2 / 13

Page 3: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – materials

Videohttps://vimeo.com/178485416 – short introduction to R Markdown.https://youtu.be/YXSp6VfZaUk – creating R Markdown filehttps://youtu.be/DNS7i2m4sB0 – R Markdown with RStudio.https://youtu.be/hODWGzpiCV0 – R Markdown tutorial.

Bookshttps://bookdown.org/yihui/rmarkdown/ – R Markdown: TheDefinitive Guide.https://github.com/rstudio/bookdown – Bookdown: AuthoringBooks and Technical Documents with R Markdown.

Tomasz Górecki (UAM) R programming 3 / 13

Page 4: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Markdown

Markdown is a simple formatting language designed to make authoringcontent easy for everyone. Rather than write in complex markup code(e.g. HTML or LaTeX), you write in plain text with formatting cues.pandoc uses these cues to turn your document into attractive output.

Tomasz Górecki (UAM) R programming 4 / 13

Page 5: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – create document

Creating documents with R Markdown starts with an .Rmd file thatcontains a combination of markdown (content with simple textformatting) and R code chunks. The .Rmd file is fed to knitr, whichexecutes all of the R code chunks and creates a new markdown (.md)document which includes the R code and it’s output. The markdown filegenerated by knitr is then processed by pandoc which is responsible forcreating a finished web page, PDF, MS Word document or other format.This may sound complicated, but R Markdown makes it extremely simpleby encapsulating all of the above processing into a single render function.

Tomasz Górecki (UAM) R programming 5 / 13

Page 6: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – output formats

You can create many types of output from a single .Rmd file. R Markdownhas built in support for HTML, PDF, MS Word, ODT, RTF, Markdown,and Github flavored Markdown documents; Beamer, slidy.js, ioslides, andreveal.js slideshows; and websites, dashboards, books, handouts, packagevignettes, and Shiny apps.

Tomasz Górecki (UAM) R programming 6 / 13

Page 7: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – structure of document

There are three basic components of an R Markdown document:metadata,text,code.

The metadata is written between the pair of three dashes —. The syntaxfor the metadata is YAML, so sometimes it is also called the YAMLmetadata or the YAML frontmatter. The body of a document follows themetadata. The syntax for text is Markdown. There are two types ofcomputer code:

A code chunk starts with three backticks like ```r where r indicatesthe language name, and ends with three backticks.An inline R code expression starts with `r and ends with a backtick `.

Tomasz Górecki (UAM) R programming 7 / 13

Page 8: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R code chunks

Within an R Markdown file, R code chunks can be embedded with thenative Markdown syntax for fenced code regions.

Tomasz Górecki (UAM) R programming 8 / 13

Page 9: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Inline R code

You can also evaluate R expressions inline by enclosing the expressionwithin a single back-tick qualified with ’r’.

Tomasz Górecki (UAM) R programming 9 / 13

Page 10: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Formatting text

header 1: # header 1header 2: ## header 2header 3: ### header 3header 4: #### header 4bold: **text**italics: *text*link: [link](text)Image: Logo ![Logo](img/logo.png)LaTeX: $A = \pi \times r^{2}$

Tomasz Górecki (UAM) R programming 10 / 13

Page 11: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Selected instructions for code chunks

eval – Is the code run and the results included in the output?include – Are the code and the results included in the output (thecode is still run)?echo – Is the code displayed alongside the results.warning – Are warning messages displayed.error – Are error messages displayed.message – Are messages displayed.cache – Are the results cached for future renders.dev – format of generated images (default PNG).fig.width – Width (in inches) of the plots.fig.height – Height (in inches) of the plots.fig.align – Align of the plots: “left”, “right”, “center”.

Tomasz Górecki (UAM) R programming 11 / 13

Page 12: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – cheatsheet

```{r results = 'asis'} knitr::kable(data, caption = "Table with kable”) ``` ```{r results = "asis"} print(xtable::xtable(data, caption = "Table with xtable”), type = "html", html.table.attributes = "border=0")) ``` ```{r results = "asis"} stargazer::stargazer(data, type = "html", title = "Table with stargazer") ```

Plain text End a line with two spaces to start a new paragraph. *italics* and **bold** `verbatim code` sub/superscript^2^~2~ ~~strikethrough~~ escaped: \* \_ \\ endash: --, emdash: --- equation: $A = \pi*r^{2}$ equation block:

$$E = mc^{2}$$

> block quote

# Header1 {#anchor}

## Header 2 {#css_id}

### Header 3 {.css_class}

#### Header 4

##### Header 5

###### Header 6

<!--Text comment-->

\textbf{Tex ignored in HTML} <em>HTML ignored in pdfs</em>

<http://www.rstudio.com> [link](www.rstudio.com) Jump to [Header 1](#anchor) image:

![Caption](smallorb.png)

* unordered list + sub-item 1 + sub-item 2 - sub-sub-item 1 * item 2

Continued (indent 4 spaces) 1. ordered list 2. item 2 i) sub-item 1 A. sub-sub-item 1

(@) A list whose numbering

continues a!er

(@) an interruption

Term 1

: Definition 1

| Right | Le! | Default | Center | |------:|:-----|---------|:------:| | 12 | 12 | 12 | 12 | | 123 | 123 | 123 | 123 | | 1 | 1 | 1 | 1 |

- slide bullet 1 - slide bullet 2

(>- to have bullets appear on click)

horizontal rule/slide break:

***

A footnote [^1]

[^1]: Here is the footnote.

Write with syntax on the le! to create e"ect on right (a!er render)Pandoc’s Markdown Set render options with YAML

When you render, R Markdown 1. runs the R code, embeds results and text into .md file with knitr 2. then converts the .md file into the finished format with pandoc

Create a Reusable Template1. Create a new package with a inst/rmarkdown/templates directory 2. In the directory, Place a folder that contains:template.yaml (see below) skeleton.Rmd (contents of the template)any supporting files 3. Install the package 4. Access template in wizard at File ▶ New File ▶ R Markdown template.yaml

Set a document’s default output format in the YAML header:

--- output: html_document --- # Body

output value createshtml_document htmlpdf_document pdf (requires Tex )word_document Microso! Word (.docx)odt_document OpenDocument Textrtf_document Rich Text Formatmd_document Markdowngithub_document Github compatible markdownioslides_presentation ioslides HTML slidesslidy_presentation slidy HTML slidesbeamer_presentation Beamer pdf slides (requires Tex)

Customize output with sub-options (listed to the right):

--- output: html_document: code_folding: hide toc_float: TRUE --- # Body

Indent 4 spaces

Indent 2 spaces

html tabsets Use tablet css class to place sub-headers into tabs

# Tabset {.tabset .tabset-fade .tabset-pills} ## Tab 1 text 1 ## Tab 2 text 2 ### End tabset

Tabset

text 1 End tabset

Tab 1 Tab 2

--- name: My Template —

sub-option descriptioncitation_package The LaTeX package to process citations, natbib, biblatex or none X X Xcode_folding Let readers to toggle the display of R code, "none", "hide", or "show" Xcolortheme Beamer color theme to use Xcss CSS file to use to style document X X Xdev Graphics device to use for figure output (e.g. "png") X X X X X X Xduration Add a countdown timer (in minutes) to footer of slides Xfig_caption Should figures be rendered with captions? X X X X X X Xfig_height, fig_width Default figure height and width (in inches) for document X X X X X X X X X Xhighlight Syntax highlighting: "tango", "pygments", "kate","zenburn", "textmate" X X X X Xincludes File of content to place in document (in_header, before_body, a!er_body) X X X X X X X Xincremental Should bullets appear one at a time (on presenter mouse clicks)? X X Xkeep_md Save a copy of .md file that contains knitr output X X X X X Xkeep_tex Save a copy of .tex file that contains knitr output X Xlatex_engine Engine to render latex, "pdflatex", "xelatex", or "lualatex" X Xlib_dir Directory of dependency files to use (Bootstrap, MathJax, etc.) X X Xmathjax Set to local or a URL to use a local/URL version of MathJax to render equations X X Xmd_extensions Markdown extensions to add to default definition or R Markdown X X X X X X X X X Xnumber_sections Add section numbering to headers X Xpandoc_args Additional arguments to pass to Pandoc X X X X X X X X X Xpreserve_yaml Preserve YAML front matter in final document? Xreference_docx docx file whose styles should be copied when producing docx output Xself_contained Embed dependencies into the doc X X Xslide_level The lowest heading level that defines individual slides Xsmaller Use the smaller font size in the presentation? Xsmart Convert straight quotes to curly, dashes to em-dashes, … to ellipses, etc. X X Xtemplate Pandoc template to use when rendering file quarterly_report.html). X X X X Xtheme Bootswatch or Beamer theme to use for page X Xtoc Add a table of contents at start of document X X X X X X Xtoc_depth The lowest level of headings to add to table of contents X X X X X Xtoc_float Float the table of contents to the le! of the main content X

htm

l

pdf

wor

d

odt

rtf

md

iosl

ides

slid

y

beam

er

gitu

hb

Table Suggestions Citations and BibliographiesSeveral functions format R data into tables

Learn more in the stargazer,

xtable, and knitr packages.

Create citations with .bib, .bibtex, .copac, .enl, .json, .medline, .mods, .ris, .wos, and .xml files

1. Set bibliography file and CSL 1.0 Style file (optional) in the YAML header

2. Use citation keys in text

3. Render. Bibliography will be added to end of document

Smith cited [@smith04]. Smith cited without author [-@smith04]. @smith04 cited in line.

--- bibliography: refs.bib csl: style.csl ---

data <- faithful[1:4, ]

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at rmarkdown.rstudio.com • rmarkdown 1.6 • Updated: 2016-02

rmarkdown

Tomasz Górecki (UAM) R programming 12 / 13

Page 13: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

R Markdown – cheatsheet

Publish on RStudio Connect, to share R Markdown documents securely, schedule automatic updates, and interact with parameters in real time. www.rstudio.com/products/connect/

One or more lines surrounded with ```{r} and ```. Place chunk options within curly braces, a!er r. Insert with

YAML Header Optional section of render (e.g. pandoc) options written as key:value pairs (YAML). At start of file Between lines of - - - TextNarration formatted with markdown, mixed with: Code ChunksChunks of embedded code. Each chunk: Begins with ```{r} ends with ``` R Markdown will run the code and append the results to the doc. It will use the location of the .Rmd file as the working directory

Interactive DocumentsTurn your report into an interactive Shiny document in 4 steps 1. Add runtime: shiny to the YAML header. 2. Call Shiny input functions to embed input objects. 3. Call Shiny render functions to embed reactive output. 4. Render w rmarkdown::run or click Run Document in RStudio IDE

--- output: html_document runtime: shiny ---

```{r, echo = FALSE} numericInput("n", "How many cars?", 5)

renderTable({ head(cars, input$n) }) ```

Embed a complete app into your document with shiny::shinyAppDir()

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • [email protected] • 844-448-1212 • rstudio.com • Learn more at rmarkdown.rstudio.com • rmarkdown 1.6 • Updated: 2016-02

R Markdown : : CHEAT SHEET

Open a new .Rmd file at File ▶ New File ▶ R Markdown. Use the wizard that opens to pre-populate the file with a template Write document by editing template

Knit document to create report; use knit button or render() to knit

Preview Output in IDE window

Publish (optional) to web server Examine build log in R Markdown console

Use output file that is saved along side .Rmd

1

23

4567

modify chunk options

run all previous chunks

run current chunk

insert code chunk go to

code chunk

run code chunk(s)

1

2

3 4

5

6

7

publish

show outline

synch publish button to accounts at rpubs.com, shinyapps.io RStudio Connect

Reload document

Find in document

File path to output document

set preview location

What is R Markdown?

Insert with `r <code>`. Results appear as text without code.

Options not listed above: R.options, aniopts, autodep, background, cache.comments, cache.lazy, cache.rebuild, cache.vars, dev, dev.args, dpi, engine.opts, engine.path, fig.asp, fig.env, fig.ext, fig.keep, fig.lp, fig.path, fig.pos, fig.process, fig.retina, fig.scap, fig.show, fig.showtext, fig.subcap, interval, out.extra, out.height, out.width, prompt, purl, ref.label, render, size, split, tidy.opts

Embed code with knitr syntaxBuilt with `r getRversion()` Built with 3.2.3

INLINE CODE CODE CHUNKS

```{r echo=TRUE} getRversion() ```

Set with knitr::opts_chunk$set(), e.g.GLOBAL OPTIONS

```{r include=FALSE} knitr::opts_chunk$set(echo = TRUE) ```

Use rmarkdown::render() to render/knit at cmd line. Important args:

Workflow

input - file to render output_format

render

ParametersParameterize your documents to reuse with new inputs (e.g., data, values, etc.)

--- params: n: 100 d: !r Sys.Date() ---

Today’s date is `r params$d`

1. Add parameters · Create and set parameters in the header as sub-values of params

2. Call parameters · Call parameter values in code as params$<name>

3. Set parameters · Set values wth Knit with parameters or the params argument of render(): render("doc.Rmd", params = list(n = 1, d = as.Date("2015-01-01"))

output_options - List of render options (as in YAML)

output_file output_dir

params - list of params to use

envir - environment to evaluate code chunks in

encoding - of input file

.rmd Structure.Rmd files · An R Markdown (.Rmd) file is a record of your research. It contains the code that a scientist needs to reproduce your work along with the narration that a reader needs to understand your work. Reproducible Research · At the click of a button, or the type of a command, you can rerun the code in an R Markdown file to reproduce your work and export the results as a finished report. Dynamic Documents · You can choose to export the finished report in a variety of formats, including html, pdf, MS Word, or RTF documents; html or pdf based slides, Notebooks, and more.

cache - cache results for future knits (default = FALSE) cache.path - directory to save cached results in (default = "cache/") child - file(s) to knit and then include (default = NULL) collapse - collapse all output into single block (default = FALSE) comment - prefix for each line of results (default = '##')

dependson - chunk dependencies for caching (default = NULL) echo - Display code in output document (default = TRUE) engine - code language used in chunk (default = 'R') error - Display error messages in doc (TRUE) or stop render when errors occur (FALSE) (default = FALSE) eval - Run code in chunk (default = TRUE)

message - display code messages in document (default = TRUE) results (default = 'markup')'asis' - passthrough results'hide' - do not display results'hold' - put all results below all code tidy - tidy code for display (default = FALSE) warning - display code warnings in document (default = TRUE)

fig.align - 'le!', 'right', or 'center' (default = 'default') fig.cap - figure caption as character string (default = NULL) fig.height, fig.width - Dimensions of plots in inches highlight - highlight source code (default = TRUE) include - Include chunk in doc a!er running (default = TRUE)

IMPORTANT CHUNK OPTIONS

rmarkdown

Rmd

Tomasz Górecki (UAM) R programming 12 / 13

Page 14: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

LaTeX – cheatsheet

LATEX2" Cheat Sheet

Document classesbook Default is two-sided.report No \part divisions.article No \part or \chapter divisions.letter Letter (?).slides Large sans-serif font.Used at the very beginning of a document: \documentclass{class}.Use \begin{document} to start contents and \end{document} to endthe document.

Common documentclass options10pt/11pt/12pt Font size.letterpaper/a4paper Paper size.twocolumn Use two columns.twoside Set margins for two-sided.landscape Landscape orientation. Must use dvips -t

landscape.draft Double-space lines.Usage: \documentclass[opt,opt]{class}.

Packagesfullpage Use 1 inch margins.anysize Set margins: \marginsize{l}{r}{t}{b}.multicol Use n columns: \begin{multicols}{n}.latexsym Use LATEX symbol font.graphicx Show image: \includegraphics[width=x]{file}.url Insert URL: \url{http://. . . }.Use before \begin{document}. Usage: \usepackage{package}

Title\author{text} Author of document.\title{text} Title of document.\date{text} Date.These commands go before \begin{document}. The declaration\maketitle goes at the top of the document.

Miscellaneous\pagestyle{empty} Empty header, footer and no page numbers.\tableofcontents Add a table of contents here.

Document structure\part{title}\chapter{title}\section{title}\subsection{title}

\subsubsection{title}\paragraph{title}\subparagraph{title}

Use \setcounter{secnumdepth}{x} suppresses heading numbers ofdepth > x, where chapter has depth 0. Use a *, as in\section*{title}, to not number a particular item—these items willalso not appear in the table of contents.

Text environments\begin{comment} Comment (not printed). Requires verbatim pack-

age.\begin{quote} Indented quotation block.\begin{quotation}Like quote with indented paragraphs.\begin{verse} Quotation block for verse.

Lists\begin{enumerate} Numbered list.\begin{itemize} Bulleted list.\begin{description}Description list.\item text Add an item.\item[x] text Use x instead of normal bullet or number. Re-

quired for descriptions.

References\label{marker} Set a marker for cross-reference, often of the form

\label{sec:item}.\ref{marker} Give section/body number of marker.\pageref{marker} Give page number of marker.\footnote{text} Print footnote at bottom of page.

Floating bodies\begin{table}[place] Add numbered table.\begin{figure}[place] Add numbered figure.\begin{equation}[place] Add numbered equation.\caption{text} Caption for the body.The place is a list valid placements for the body. t=top, h=here,b=bottom, p=separate page, !=place even if ugly. Captions andlabel markers should be within the environment.

Text propertiesFont faceCommand Declaration E↵ect\textrm{text} {\rmfamily text} Roman family\textsf{text} {\sffamily text} Sans serif family\texttt{text} {\ttfamily text} Typewriter family\textmd{text} {\mdseries text} Medium series\textbf{text} {\bfseries text} Bold series\textup{text} {\upshape text} Upright shape\textit{text} {\itshape text} Italic shape\textsl{text} {\slshape text} Slanted shape\textsc{text} {\scshape text} Small Caps shape\emph{text} {\em text} Emphasized\textnormal{text}{\normalfont text}Document font\underline{text} UnderlineThe command (tttt) form handles spacing better than thedeclaration (tttt) form.

Font size\tiny tiny

\scriptsize scriptsize

\footnotesize footnotesize\small small\normalsize normalsize\large large

\Large Large\LARGELARGE

\huge huge

\Huge HugeThese are declarations and should be used in the form {\small . . . },or without braces to a↵ect the entire document.

Verbatim text\begin{verbatim} Verbatim environment.\begin{verbatim*} Spaces are shown as .\verb!text! Text between the delimiting characters (in this

case ‘!’) is verbatim.

JustificationEnvironment Declaration\begin{center} \centering\begin{flushleft} \raggedright\begin{flushright} \raggedleft

Miscellaneous\linespread{x} changes the line spacing by the multiplier x.

Text-mode symbolsSymbols& \& \_ . . . \ldots • \textbullet$ \$ ˆ \^{} | \textbar \ \textbackslash% \% ˜ \~{} # \# § \S

Accentso \‘o o \’o o \^o o \~o o \=oo \.o o \"o o \c o o \v o o \H oc \c c o. \d o o

¯\b o �oo \t oo œ \oe

Œ \OE æ \ae Æ \AE a \aa A \AAø \o Ø \O l \l L \L ı \i⌘ \j ¡ ~‘ ¿ ?‘

Delimiters‘ ‘ “ ‘‘ { \{ [ [ ( ( < \textless’ ’ ” ’’ } \} ] ] ) ) > \textgreater

DashesName Source Example Usagehyphen - X-ray In words.en-dash -- 1–5 Between numbers.em-dash --- Yes—or no? Punctuation.

Line and page breaks\\ Begin new line without new paragraph.\\* Prohibit pagebreak after linebreak.\kill Don’t print current line.\pagebreak Start new page.\noindent Do not indent current line.

Miscellaneous\today March 28, 2017.$\sim$ Prints ⇠ instead of \~{}, which makes ˜.~ Space, disallow linebreak (W.J.~Clinton).\@. Indicate that the . ends a sentence when following an

uppercase letter.\hspace{l} Horizontal space of length l (Ex: l = 20pt).\vspace{l} Vertical space of length l.\rule{w}{h}Line of width w and height h.

Tabular environmentstabbing environment\= Set tab stop. \> Go to tab stop.

Tab stops can be set on “invisible” lines with \kill at the end of theline. Normally \\ is used to separate lines.

Tomasz Górecki (UAM) R programming 13 / 13

Page 15: prof. UAM dr hab. Tomasz Góreckidrizzt.home.amu.edu.pl/images/RProg/W4.pdf · 2020. 5. 8. · R programming prof. UAM dr hab. Tomasz Górecki tomasz.gorecki@amu.edu.pl Department

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

LaTeX – cheatsheet

tabular environment

\begin{array}[pos]{cols}\begin{tabular}[pos]{cols}\begin{tabular*}{width}[pos]{cols}

tabular column specification

l Left-justified column.c Centered column.r Right-justified column.p{width} Same as \parbox[t]{width}.@{decl} Insert decl instead of inter-column space.| Inserts a vertical line between columns.

tabular elements

\hline Horizontal line between rows.\cline{x-y} Horizontal line across columns x through y.\multicolumn{n}{cols}{text}

A cell that spans n columns, with cols column specifi-cation.

Math modeFor inline math, use \(...\) or $...$. For displayed math, use\[...\] or \begin{equation}.

Superscriptx ^{x} Subscriptx _{x}xy \frac{x}{y}

Pn

k=1\sum_{k=1}^n

npx \sqrt[n]{x}

Qn

k=1\prod_{k=1}^n

Math-mode symbols

\leq � \geq 6= \neq ⇡ \approx⇥ \times ÷ \div ± \pm · \cdot� ^{\circ} � \circ 0 \prime · · · \cdots1 \infty ¬ \neg ^ \wedge _ \vee� \supset 8 \forall 2 \in ! \rightarrow⇢ \subset 9 \exists /2 \notin ) \Rightarrow[ \cup \ \cap | \mid , \Leftrightarrowa \dot a a \hat a a \bar a a \tilde a↵ \alpha � \beta � \gamma � \delta✏ \epsilon ⇣ \zeta ⌘ \eta " \varepsilon✓ \theta ◆ \iota \kappa # \vartheta� \lambda µ \mu ⌫ \nu ⇠ \xi⇡ \pi ⇢ \rho � \sigma ⌧ \tau� \upsilon � \phi � \chi \psi! \omega � \Gamma � \Delta ⇥ \Theta⇤ \Lambda ⌅ \Xi ⇧ \Pi ⌃ \Sigma⌥ \Upsilon � \Phi \Psi ⌦ \Omega

Bibliography and citationsWhen using BibTEX, you need to run latex, bibtex, and latextwice more to resolve dependencies.

Citation types\cite{key} Full author list and year. (Watson and Crick 1953)\citeA{key} Full author list. (Watson and Crick)\citeN{key} Full author list and year. Watson and Crick (1953)\shortcite{key} Abbreviated author list and year. ?\shortciteA{key} Abbreviated author list. ?\shortciteN{key} Abbreviated author list and year. ?\citeyear{key} Cite year only. (1953)

All the above have an NP variant without parentheses; Ex. \citeNP.

BibTEX entry types

@article Journal or magazine article.@book Book with publisher.@booklet Book without publisher.@conference Article in conference proceedings.@inbook A part of a book and/or range of pages.@incollection A part of book with its own title.@misc If nothing else fits.@phdthesis PhD. thesis.@proceedings Proceedings of a conference.@techreport Tech report, usually numbered in series.@unpublished Unpublished.

BibTEX fields

address Address of publisher. Not necessary for major publish-ers.

author Names of authors, of format ....booktitle Title of book when part of it is cited.chapter Chapter or section number.edition Edition of a book.editor Names of editors.institution Sponsoring institution of tech. report.journal Journal name.key Used for cross ref. when no author.month Month published. Use 3-letter abbreviation.note Any additional information.number Number of journal or magazine.organization Organization that sponsors a conference.pages Page range (2,6,9--12).publisher Publisher’s name.school Name of school (for thesis).series Name of series of books.title Title of work.type Type of tech. report, ex. “Research Note”.volume Volume of a journal or book.year Year of publication.Not all fields need to be filled. See example below.

Common BibTEX style files

abbrv Standard abstract alpha with abstractalpha Standard apa APAplain Standard unsrt Unsorted

The LATEX document should have the following two lines just before\end{document}, where bibfile.bib is the name of the BibTEX file.

\bibliographystyle{plain}\bibliography{bibfile}

BibTEX exampleThe BibTEX database goes in a file called file.bib, which isprocessed with bibtex file.

@String{N = {Na\-ture}}@Article{WC:1953,

author = {James Watson and Francis Crick},title = {A structure for Deoxyribose Nucleic Acid},journal = N,volume = {171},pages = {737},year = 1953

}

Sample LATEX document\documentclass[11pt]{article}\usepackage{fullpage}\title{Template}\author{Name}\begin{document}\maketitle

\section{section}\subsection*{subsection without number}text \textbf{bold text} text. Some math: $2+2=5$\subsection{subsection}text \emph{emphasized text} text. \cite{WC:1953}discovered the structure of DNA.

A table:\begin{table}[!th]\begin{tabular}{|l|c|r|}\hlinefirst & row & data \\second & row & data \\\hline\end{tabular}\caption{This is the caption}\label{ex:table}\end{table}

The table is numbered \ref{ex:table}.\end{document}

Copyright c� 2014 Winston Changhttp://wch.github.io/latexsheet/

Tomasz Górecki (UAM) R programming 13 / 13